我有一个非常简单的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?
}
}
}
}
答案 0 :(得分:2)
一种方法是隐藏/取消隐藏应用程序本身
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)
}
})
}