13

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".

Ky -
  • 30,724
  • 51
  • 192
  • 308
esaruoho
  • 896
  • 1
  • 7
  • 25

3 Answers3

25

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.

David Monagle
  • 1,701
  • 16
  • 19
13

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
    ...
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • I added window.title = "the title", and now it shows. Thanks for the advice, @Asperi, marking this as solved :) – esaruoho Jan 19 '20 at 08:33
0

if You have only ONE ContentView

(that was created in AppDelegate with: window.contentView = NSHostingView(rootView: contentView) as per Apple single View App..)

You can do in your ContentView:

private func setTitle(title: String) {
    if let ad = NSApplication.shared.delegate as? AppDelegate{
        ad.window.title = title
    }
}

(seems a bit orribile.. remember me old days of iOS 2.11, with abuse of App Delegate... story returns)

ingconti
  • 10,876
  • 3
  • 61
  • 48