在 AppKit 中为 macOS SwiftUI 应用程序设置主 window 标题?

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

我有一个简单的 WKWebView 应用程序,它使用 AppKit 中的 SwiftUI 在 macOS 上打开一个网站。 但是,应用程序 window 没有标题 - 我说的是第一行(用红色 X 关闭它,等等

如何在那里设置标题?我试过查看 Main.Storyboard,但没有看到任何类似于“标题段”的内容。

Window是在AppDelegate中创建的,所以你可以按照下面的方式来做...

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

如果您只有一个 ContentView

(这是在 AppDelegate 中创建的:window.contentView = NSHostingView(rootView: contentView) 根据 Apple 单视图应用程序..)

您可以在 ContentView 中执行:

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

(看起来有点不对劲..记得我过去的日子 iOS 2.11,滥用 App Delegate...故事 returns)

从 MacOS 11 开始,window 标题可以在视图上使用 .navigationTitle 设置。例如:

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

来自 Apple 的帮助:

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.