如何从视图中取消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>) {
    }
}
相关推荐
Andy Dennis1 天前
ios开发 xcode配置
ios·cocoa·xcode
DisonTangor4 天前
通义实验室开源端到端语音识别大模型—— Fun-ASR-Nano-2512
人工智能·语音识别·xcode
用户40538369354 天前
开源语音识别FunASR入门详解
ide·macos·xcode
Unstoppable227 天前
iOS App 开发攻略
ios·xcode·软件开发
王者鳜錸9 天前
短语音多语种混合识别-GUI界面开发
ide·macos·xcode
WeiAreYoung11 天前
uni-app xcode 制作iOS Notification Service Extension 远程推送图文原生插件
ios·uni-app·xcode
2501_9159184111 天前
iOS App 测试方法,Xcode、TestFlight与克魔(KeyMob)等工具组合使用
android·macos·ios·小程序·uni-app·iphone·xcode
小胖红12 天前
Xcode 打包失败 处理
ide·macos·xcode
PKWjiMrlayO13 天前
LabView源码与三菱FX编程口协议通讯的实现方案
xcode
牛奔17 天前
Go语言中结构体转Map优雅实现
开发语言·后端·macos·golang·xcode