如何从视图中取消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>) {
    }
}
相关推荐
大熊猫侯佩12 小时前
桃花岛 Xcode 构建秘籍:Swift 中的 “Feature Flags” 心法
app·xcode·swift
悄然林静13 小时前
Mac终端执行`brew doctor`报`openssl@1.1`警告
mac·xcode·apple
权咚1 天前
阿权的开发经验小集
git·ios·xcode
龙腾-虎跃2 天前
FreeSWITCH FunASR语音识别模块
人工智能·语音识别·xcode
2501_915106322 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
zhanggui2 天前
iOS Debug Symbols
ios·xcode·debug symbox
百思可瑞教育4 天前
使用UniApp实现一个AI对话页面
javascript·vue.js·人工智能·uni-app·xcode·北京百思可瑞教育·百思可瑞教育
开开心心loky6 天前
[iOS] 属性关键字
macos·ios·objective-c·cocoa·xcode
大熊猫侯佩8 天前
10 个 Xcode 神技:哥谭开发者必学的 IDE 对抗术
xcode·swift·apple
Winter_Sun灬8 天前
Mac开发第一步 - 安装Xcode
ide·macos·xcode