簡體   English   中英

跟蹤 NSWindow 焦點? (斯威夫特,macOS)

[英]Track NSWindow focus? (Swift, macOS)

我正在嘗試跟蹤創建的 Windows 焦點,以便我可以對這些事件執行操作。

我可以使用NSView.frameDidChangeNotification跟蹤通知中心的窗口框架尺寸,但我找不到使用NSWindowDidResignKeyNotificationNSWindowDidResignMainNotification類的正確方法。

private func newWindow() {
    let windowInfo  = WindowInfo()
    let contentView = ContentView()
        .environmentObject(windowInfo)

    let window = NSWindow(
        contentRect: NSRect(x: 0, y: 0, width: 350, height: 600),
        styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
        backing: .buffered,
        defer: false
    )

    window.isReleasedWhenClosed                         = false
    window.contentView                                  = NSHostingView(rootView: contentView)
    window.contentView?.postsFrameChangedNotifications  = true
    window.makeKeyAndOrderFront(nil)

    // vvv  I'm trying to use a similar method of being notified when a created window loses/regains focus.  vvv
    //                                                          v v v
    NotificationCenter.default.addObserver(forName: NSView.frameDidChangeNotification, object: nil, queue: nil) { (notification) in
        windowInfo.frame = window.frame
    }
}

另外,如果有一些方法可以在 SwiftUI 中檢測窗口焦點,我也可以使用它。 執行操作的通知適用於我在 SwiftUI 中的視圖

這只是我的一個愚蠢的疏忽(已經很晚了),我找到了我需要的線路。

添加NSWindow.didBecomeKeyNotification可以正確捕獲焦點事件。

還將object: nil更改為object: window確保捕獲的焦點事件僅針對特定窗口,而不是全部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM