NSPopover 未关闭

Joh*_*ard 2 macos nspopover swift

如果用户单击菜单图标以显示弹出框,如果用户单击弹出框以外的任何位置,弹出框将关闭,我会尝试这样做。我将行为设置为瞬态,但那不是我想的那样。

现在,如果用户单击弹出窗口上的某个位置将焦点移至该位置,则用户可以单击屏幕上的其他位置,弹出窗口将关闭。如果我可以强制将焦点放在 popover 上,我认为这也能解决我的问题。不幸的是,我也不知道该怎么做。

class AppDelegate: NSObject, NSApplicationDelegate {

    let view : NSView!
    let statusItem: NSStatusItem
    let popover: NSPopover
    let button : NSButton!

    override init() {

        statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
        if let statusButton = statusItem.button {
            appStatusButton = statusButton
            statusButton.image = NSImage(named: "icon128off")
            statusButton.alternateImage = NSImage(named: "icon128")
            statusButton.action = "onPress:"
        }

        popover = NSPopover()
        popover.animates = false
        popover.contentViewController = ViewController()
        popover.behavior = .Transient
    }


}
Run Code Online (Sandbox Code Playgroud)

这是视图控制器

class ViewController: NSViewController, WKNavigationDelegate{

   var webView : WKWebView!

   override func loadView() {
      view = NSView()
      view.translatesAutoresizingMaskIntoConstraints = false
      view.addConstraint(NSLayoutConstraint(
        item: view, attribute: .Width, relatedBy: .Equal,
        toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 580))
      view.addConstraint(NSLayoutConstraint(
        item: view, attribute: .Height, relatedBy: .Equal,
        toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 425))

    }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ard 6

斯威夫特 5:

NSApplication.shared.activate(ignoringOtherApps: true)
Run Code Online (Sandbox Code Playgroud)

在打开弹出窗口之前添加这个

NSApplication.sharedApplication().activateIgnoringOtherApps(true)
Run Code Online (Sandbox Code Playgroud)

感谢这个人!


vau*_*all 5

Swift 5.1

Problem is that the PopOver's Window is not becoming key, to fix this just force it to become key just after showing it. For example supposing pop is a NSPopOver:

pop.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
pop.contentViewController?.view.window?.makeKey()
Run Code Online (Sandbox Code Playgroud)