【问题标题】:Setting a main window title for macOS SwiftUI app in AppKit?在 AppKit 中为 macOS SwiftUI 应用程序设置主窗口标题?
【发布时间】:2020-05-05 14:01:08
【问题描述】:

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

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

【问题讨论】:

    标签: xcode macos swiftui wkwebview appkit


    【解决方案1】:

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

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

    来自 Apple 的帮助:

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

    【讨论】:

      【解决方案2】:

      窗口是在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 的建议,将其标记为已解决:)
      【解决方案3】:

      如果你只有一个 ContentView

      (这是在 AppDelegate 中创建的:window.contentView = NSHostingView(rootView: contentView) 根据 Apple 单一 View App..)

      你可以在你的 ContentView 中做:

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

      (似乎有点可恶.. 记得我在 iOS 2.11 的旧时光,滥用 App Delegate...故事回归)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        • 2021-08-11
        • 2021-04-15
        • 2020-04-10
        相关资源
        最近更新 更多