【问题标题】:Window Control Buttons Missing from New Window in SwiftUI AppSwiftUI 应用程序中的新窗口中缺少窗口控制按钮
【发布时间】:2021-05-10 05:03:50
【问题描述】:

从 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)
  }
}

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

但是当我点击Open Preferences后,我看到一个新窗口出现如下: 为什么弹出窗口中缺少控制按钮(关闭、最小化、缩放)?

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

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

我在 AppKit 应用程序中使用了相同的示例,因此 SwiftUI 似乎有些奇怪。有什么想法吗?

【问题讨论】:

    标签: swiftui nswindow nswindowcontroller


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      相关资源
      最近更新 更多