如何从视图中取消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>) {
    }
}
相关推荐
声网1 天前
如何用 Fun-ASR-Nano 微调一个「听懂行话」的语音模型?丨Voice Agent 学习笔记
笔记·学习·xcode
我不是8神3 天前
go语言语法基础全面总结
开发语言·golang·xcode
2501_941881404 天前
在墨西哥城复杂流量环境下构建高稳定性API网关的架构设计与实现实践分享
macos·golang·xcode
麦兜*4 天前
【Swift】苹果App开发全流程解析:从Xcode配置到App Store上架避坑指南
xcode·swift
好大哥呀5 天前
如何在iOS中使用UIViewController的生命周期方法?
macos·ios·xcode
我要用代码向我喜欢的女孩表白10 天前
对象存储路径文件1TB以上文件比对,go语言
ios·golang·xcode
_Voosk11 天前
macOS Xcode C++程序设置相对路径根目录
c语言·c++·xcode·swift
bybitq14 天前
Go 语言之旅方法(Methods)与接口(Interfaces)完全指南
开发语言·golang·xcode
海上彼尚14 天前
Go之路 - 8.go的接口
开发语言·golang·xcode
思成Codes16 天前
Gin路由:构建高效RESTful API
golang·restful·xcode·gin