AppDelegate中有一个类似这样的方法:
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
return true
}
通过使用这个函数,在这个函数中,我们可以得到hasVisibleWindows
的true或false,我的问题是,我想在函数之外访问hasVisibleWindows的值,而且函数工作的方式是,我们应该点击图标来使函数工作,在我的问题中,我想在不点击图标的情况下获得hasVisibleWindows的值,有没有其他方法可以知道应用程序NSApplication.shared
是否有可见的窗口?
更新:
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
private lazy var window1: NSWindow = NSWindow()
private lazy var window2: NSWindow = NSWindow()
func applicationDidFinishLaunching(_ aNotification: Notification) {
buildWindow()
}
private func buildWindow() {
window1 = makeWindow(title: "Window 1", isReleasedWhenClosed: false)
window2 = makeWindow(title: "Window 2", isReleasedWhenClosed: false)
// You can close the windows or minimize them and it will return false, if you let just 1 window open it will return true.
// You can try all posibale things in 5 sec, close both windows or minimize both or what you like.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(5)) {
print(nsApplication.hasVisibleWindows)
}
}
}
@discardableResult
func makeWindow(title: String, isReleasedWhenClosed: Bool) -> NSWindow {
let window: NSWindow = NSWindow()
window.styleMask = [.titled, .closable, .miniaturizable, .resizable]
window.backingType = .buffered
window.isReleasedWhenClosed = isReleasedWhenClosed
window.setFrame(CGRect(origin: .zero, size: CGSize(width: 400.0, height: 200.0)), display: true)
window.title = title
window.center()
window.setFrameAutosaveName(window.title)
window.isMovableByWindowBackground = true
window.makeKeyAndOrderFront(window)
return window
}
extension NSApplication {
var hasVisibleWindows: Bool {
for item in NSApplication.shared.orderedWindows {
if (item.isVisible) { return true }
}
return false
}
}
// main part:
let nsApplication: NSApplication = NSApplication.shared
let appDelegate: AppDelegate = AppDelegate()
nsApplication.delegate = appDelegate
nsApplication.run()
1条答案
按热度按时间6ojccjat1#
NSApplication
有一个windows
数组。你想要的值只是这个数组是否包含任何isVisible
为true的东西。如果你想匹配
flag
参数的行为,你还需要检查isMiniaturized
,因为很明显,有一个小型化的窗口也会导致true
被传递给标志。来自
applicationShouldHandleReopen
的docs。小型化窗口,Dock中的窗口,被认为是可见的,并导致flag返回true,尽管小型化窗口在发送
isVisible
消息时返回false。所以表达式应该是: