如何从视图中取消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>) {
    }
}
相关推荐
会游泳的石头4 天前
在Java项目中实现本地语音识别与热点检测,并集成阿里云智能语音服务(优化版)
阿里云·语音识别·xcode
江鸟199810 天前
AI日报 · 2025年5月03日|Perplexity 集成 WhatsApp,苹果传与 Anthropic 合作开发 Xcode
人工智能·gpt·macos·大模型·agent·xcode·智能体
桌角的眼镜12 天前
模拟开发授权平台
macos·ios·xcode
BianHuanShiZhe13 天前
升级xcode15 报错Error (Xcode): Cycle inside Runner
ide·macos·xcode
明似水15 天前
如何解决 Xcode 签名证书和 Provisioning Profile 过期问题
macos·xcode
言之。15 天前
Go 语言中的 `os.Truncate` 函数详解
ios·golang·xcode
桃花仙丶16 天前
iOS/Flutter混合开发之PlatformView配置与使用
flutter·ios·xcode·swift·dart
薛瑄17 天前
FFmpeg之三 录制音频并保存, API编解码从理论到实战
ffmpeg·音视频·xcode
cauyyl20 天前
xcode 16 遇到contains bitcode
react native·xcode
A_ugust__20 天前
Vue3集成浏览器API实时语音识别
人工智能·语音识别·xcode