如何在 macOS(不是 iOS)上的 SwiftUI 中以编程方式从后台打开应用程序窗口?



我有一个非常简单的 SwiftUI 应用程序,它在菜单栏中运行,应该定期从后台的重复计时器内打开一个应用程序窗口(整个应用程序中只有一个窗口/视图(。

如何实际从代码打开应用窗口?

下面是一个简化的AppDelegate.swift示例,显示了我正在尝试执行的操作:

import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {  
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Create the window and set the content view. 
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
var loop = 0
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
loop+=1
if (loop % 10 == 0) {
// TODO: How to close the window?
} else {
// TODO: How to reopen the window?
}
}
}
}

一种方法是隐藏/取消隐藏应用程序本身

func applicationDidFinishLaunching(_ aNotification: Notification) {
//setup of window etc ...
Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { _ in
if self.window.isVisible {
NSApp.hide(self)
} else {
NSApp.unhide(self)
}
})
}

相关内容

最新更新