![](/img/trans.png)
[英]Go fullscreen with NSWindow on a second screen on macOS 10.12 with Swift 3?
[英]Track NSWindow focus? (Swift, macOS)
我正在嘗試跟蹤創建的 Windows 焦點,以便我可以對這些事件執行操作。
我可以使用NSView.frameDidChangeNotification
跟蹤通知中心的窗口框架尺寸,但我找不到使用NSWindowDidResignKeyNotification
或NSWindowDidResignMainNotification
類的正確方法。
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.