使用 PasteBoard 的更改进行 .contextMenu 更新 [英] Make a .contextMenu update with changes from PasteBoard

查看:51
本文介绍了使用 PasteBoard 的更改进行 .contextMenu 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这样的视图,我有一个 contextMenu 视图修饰符:

I have a contextMenu view modifier for a view like this one:

Text("Some Text")
.contextMenu {
    Button(action: {
        editCodes(withTappedCode: codeOnDisplay, delete: true)
    }, label: {
         Text("Paste")
         Image(systemName: "doc.on.clipboard")
    })
    .disabled(!UIPasteboard.general.contains(pasteboardTypes: [aPAsteBoardType]))
}

该按钮仅应在特定粘贴板类型可用时启用.然而,这不会发生.

The button should only be enabled when a certain Pasteboard Type is available. However this doesn't happen.

当按钮的上下文菜单第一次显示时设置为禁用状态.在此之后,对粘贴板的任何更改都不会修改禁用状态,即使关闭并再次打开菜单也是如此.

The disabled state is set when the context menu for the Button is first shown. After this any changes to the pasteboard will not modify the disabled state, even if the menu is closed and opened again.

这似乎只有在以任何方式刷新修改后的视图时才会发生.

This seems to only to happen if the modified view is refreshed in any way.

如何使用粘贴板类型更改上下文菜单按钮的禁用状态?

How can I change the disabled state, for the context menu button, with the Pasteboard type?

推荐答案

你可以通过监听UIPasteboard.changedNotification来检测变化并刷新视图:

You can listen to UIPasteboard.changedNotification to detect changes and refresh the view:

struct ContentView: View {
    @State private var pasteDisabled = false

    var body: some View {
        Text("Some Text")
            .contextMenu {
                Button(action: {}) {
                    Text("Paste")
                    Image(systemName: "doc.on.clipboard")
                }
                .disabled(pasteDisabled)
            }
            .onReceive(NotificationCenter.default.publisher(for: UIPasteboard.changedNotification)) { _ in
                pasteDisabled = !UIPasteboard.general.contains(pasteboardTypes: [aPAsteBoardType])
            }
    }
}

(您可能还想使用 UIPasteboard.removedNotification).

(You may also want to use UIPasteboard.removedNotification).

这篇关于使用 PasteBoard 的更改进行 .contextMenu 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆