如何从视图中取消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>) {
    }
}
相关推荐
mobsmobs4 天前
Flutter开发环境搭建与工具链
android·flutter·ios·android studio·xcode
mobsmobs5 天前
Flutter之Widget体系与布局原理
android·flutter·xcode·dart
水木姚姚8 天前
图书管理软件iOS(iPhone)
macos·ios·iphone·xcode·swift
Keya12 天前
lipo 命令行指南
ios·xcode·swift
大熊猫侯佩13 天前
探秘 WWDC 25 全新 #Playground 宏:提升 Swift 开发效率的超级神器
xcode·swift·wwdc
bryceZh15 天前
Cursor/VScode+iOS开发工具链
ai编程·xcode·visual studio code
andyguo16 天前
语音识别的速度革命:从 Whisper 到 Whisper-CTranslate2,我经历了什么?
人工智能·学习·ai·whisper·语音识别·xcode·ai测评
阿里超级工程师20 天前
经验分享-没有xcode也可以上传App Store Connect
xcode·上传ipa
Keya21 天前
解决 pod install 警告信息显示不完全的方法
ios·xcode·cocoapods
杂雾无尘21 天前
开发者必看,全面解析应用更新策略,让用户无法拒绝你的应用更新!
ios·xcode·swift