![](/img/trans.png)
[英]How to open a window from a menu bar popover using SwiftUI on MacOS
[英]How to programmatically open the app window from the background in SwiftUI on macOS (not iOS)?
我有一个非常简单的 SwiftUI 应用程序,它在菜单栏中运行,并且应该定期从后台的重复计时器中打开一个应用程序 window(整个应用程序中只有一个窗口/视图)。
如何从代码中实际打开应用程序 window?
这是一个简化的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)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.