如何从视图中取消nspopover?

我正在使用Swift和SwiftUI编写一个MacOS。我对此真的很陌生,但我是一个经验丰富的程序员。

该应用程序是一个带有一个NSPopover的菜单栏应用程序。在AppDelegate中,我包括:

self.popover = NSPopover()
self.popover.contentViewController = NSHostingController(rootView: contentView)

复制

contentView中,是否可以包含一个关闭弹出窗口的按钮?

Stack Overflow用户

发布于 2020-09-16 16:59:01

您可以在响应器链中找到NSPopover,然后将其关闭。要实现这一点,您应该为close按钮创建一个协调器:

struct CloseButton: NSViewRepresentable {

    class Coordinator: NSObject {
        @objc func click(_ button: NSButton) {
            var responder: NSResponder? = button
            while responder != nil {
                responder = responder?.nextResponder
                if let popover = responder as? NSPopover {
                    popover.close()
                    break
                }
            }
        }
    }

    func makeNSView(context: NSViewRepresentableContext<Self>) -> NSButton {
        NSButton(title: "Close", target: context.coordinator, action: #selector(Coordinator.click(_:)))
    }
    
    func makeCoordinator() -> CloseButton.Coordinator {
        return Coordinator()
    }
    
    func updateNSView(_ nsView: NSButton, context: NSViewRepresentableContext<Self>) {
    }
}
相关推荐
HMS Core5 天前
实时语音交互,打造更加智能便捷的应用
macos·华为·交互·xcode·harmonyos
丁乾坤的博客5 天前
Xcode手动安装SDK模拟器
sdk·xcode·模拟器·手动
Se7en丶潇洒哥7 天前
Xcode 16 上传AppStore遇到第三方库 bitcode 的问题
ios·xcode·appstore·xcode 16·bitcode
刘小哈哈哈8 天前
iOS 使用使用渐变色生成图片
ios·cocoa·xcode
RollingPin9 天前
Xcdoe快速更新安装的小Tips
xcode·xcode更新·simulator·xcode16·xcode安装·安装模拟器·ios18
面壁者LOGIC9 天前
Invalid Executable The executable contains bitcode
ios·xcode
一只蜗牛儿9 天前
自动驾驶综述 | 定位、感知、规划常见算法汇总
人工智能·macos·xcode
请叫我飞哥@9 天前
Xcode 16 Pod init 报错
ide·macos·xcode
bugtraq202110 天前
Fyne ( go跨平台GUI )中文文档- 扩展Fyne (七)
开发语言·golang·xcode
骨子里的偏爱10 天前
Xcode报错:The request was denied by service delegate (SBMainWorkspace)
ide·macos·xcode