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

14

我有一个简单的WKWebView应用程序,在macOS中使用SwiftUI在AppKit上打开网站。

但是,应用程序窗口没有标题-我指的是顶部行(带有红色X关闭它等)。

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

3个回答

27
自 MacOS 11 起,可以使用 .navigationTitle 在 View 上设置窗口标题。例如:
    WindowGroup {
        ContentView()
            .navigationTitle("Hello!")
    }

来自苹果帮助文档:

视图的导航标题用于在界面上显示当前导航状态。在 iOS 和 watchOS 上,当在导航视图内导航到一个视图时,该视图的标题会显示在导航栏中。在 iPadOS 上,主目标的导航标题会反映为应用切换器中窗口的标题。同样,在 macOS 上,主目标的标题用作标题栏、Windows 菜单和任务控制中的窗口标题。


13

窗口是在 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
    ...

我添加了window.title = "the title",现在它显示出来了。感谢您的建议,@Asperi,将其标记为已解决 :) - esaruoho

0

如果您只有一个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...故事继续)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接