如何从视图中取消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>) {
    }
}
相关推荐
大熊猫侯佩5 小时前
「内力探查术」:用 Instruments 勘破 SwiftUI 卡顿迷局
swiftui·debug·xcode
Magnetic_h6 小时前
【iOS】锁的原理
笔记·学习·macos·ios·objective-c·cocoa·xcode
Code季风9 天前
深入理解 Gin 框架的路由机制:从基础使用到核心原理
ide·后端·macos·go·web·xcode·gin
0wioiw014 天前
Apple基础(Xcode⑤-Flutter-Singbox-AI提示词)
flutter·macos·xcode
0wioiw015 天前
Apple基础(Xcode②-Flutter结构解析)
flutter·macos·xcode
0wioiw015 天前
Apple基础(Xcode④-Flutter-Platform Channels)
flutter·macos·xcode
胡桃夹夹子16 天前
xcode swift项目运行、连接真机运行报错,引入文件夹失败
cocoa·xcode·swift
我现在不喜欢coding18 天前
混乱的scheme、.xcconfig、build Settings梳理的清清楚楚
ios·xcode
0wioiw019 天前
Apple基础(Xcode①-项目结构解析)
ide·macos·xcode