Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a main window title for macOS SwiftUI app in AppKit?

I have a simplistic WKWebView app that opens up a website on macOS, using SwiftUI in AppKit. However, the app window has no title - I'm talking of the top row (with the red X to close it, etc.

How do I set a title there? I've tried looking at Main.Storyboard but am not seeing anything resembling a "title segment".

like image 799
esaruoho Avatar asked Jan 19 '20 08:01

esaruoho


2 Answers

As of MacOS 11, the window title can be set using .navigationTitle on a View. For example:

    WindowGroup {
        ContentView()
            .navigationTitle("Hello!")
    }

From Apple's help:

A view’s navigation title is used to visually display the current navigation state of an interface. On iOS and watchOS, when a view is navigated to inside of a navigation view, that view’s title is displayed in the navigation bar. On iPadOS, the primary destination’s navigation title is reflected as the window’s title in the App Switcher. Similarly on macOS, the primary destination’s title is used as the window title in the titlebar, Windows menu and Mission Control.

like image 112
David Monagle Avatar answered Feb 07 '23 01:02

David Monagle


Window is created in AppDelegate, so you can do it as below...

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.title = "Some title" // << assign title here
    ...
like image 23
Asperi Avatar answered Feb 07 '23 01:02

Asperi