SwiftUI 应用程序中的新窗口中缺少窗口控制按钮

问题描述

从 Xcode 中的一个SwiftUI macOS 项目开始,我设置了一些非常基本的功能

@main
struct SwiftUIWindowTestApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

//ContentView
struct ContentView: View {
  var body: some View {
    //Button to open a new window
    Button("Open Preferences"){
      openPreferences()
    }
    .padding(100)
  }
  
  //Open the new window
  func openPreferences(){
    let preferencesWindow = NSWindow()
    preferencesWindow.contentView = NSHostingView(rootView: PreferencesView())
    let controller = NSWindowController(window: preferencesWindow)
    controller.showWindow(nil)
  }
}

//PreferencesView
struct PreferencesView: View {
  var body: some View {
    Text("Preferences")
      .frame(width:300,height:200)
  }
}

在应用启动时,我看到了我的期望:

enter image description here

但是在我单击打开首选项后,我看到一个新窗口如下所示:

enter image description here

为什么该弹出窗口上缺少控制按钮(关闭、最小化、缩放)?

我已尝试将按钮显式设置为可见(即使认情况下它们应该是可见的)并且没有任何变化:

preferencesWindow.standardWindowButton(.closeButton)?.isHidden = false
preferencesWindow.standardWindowButton(.miniaturizeButton)?.isHidden = false
preferencesWindow.standardWindowButton(.zoomButton)?.isHidden = false

我有同样的示例在 AppKit 应用程序中运行良好,因此 SwiftUI 似乎有些奇怪。有什么想法吗?

解决方法

看起来 NSWindow 会创建一个这样的窗口,除非您在其上设置托管控制器。你的代码的这个修改版本对我有用:

func openPreferences(){
    let preferencesWindow = NSWindow(contentViewController: NSHostingController(rootView: PreferencesView()))
    let controller = NSWindowController(window: preferencesWindow)
    controller.showWindow(nil)
  }