简体   繁体   中英

How to programmatically open the app window from the background in SwiftUI on macOS (not iOS)?

I have a very simple SwiftUI app that runs in the menu bar and should periodically open an app window (there is only one window/view in the whole app) from inside a repeating timer in the background.

How do I actually open the app window from code?

Here's a simplified AppDelegate.swift example showing what I'm trying to do:

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?
            }
        }
    }
}

One approach is to hide/unhide the application itself

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)
        }
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM