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

esa*_*oho 5 macos xcode appkit wkwebview swiftui

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

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

Asp*_*eri 11

窗口是在 中创建的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
    ...
Run Code Online (Sandbox Code Playgroud)


Dav*_*gle 5

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

    WindowGroup {
        ContentView()
            .navigationTitle("Hello!")
    }
Run Code Online (Sandbox Code Playgroud)

来自苹果的帮助:

视图的导航标题用于直观地显示界面的当前导航状态。在 iOS 和 watchOS 上,当视图导航到导航视图内部时,该视图的标题会显示在导航栏中。在 iPadOS 上,主要目的地的导航标题在 App Switcher 中反映为窗口的标题。同样在 macOS 上,主要目的地的标题用作标题栏、Windows 菜单和任务控制中的窗口标题。