【问题标题】:SwiftUI on MacOS. - Opening a new WindowMacOS 上的 SwiftUI。 - 打开一个新窗口
【发布时间】:2021-07-24 09:49:09
【问题描述】:

在我的 MacOS SwiftUI 应用程序中,我想在新 Windows 中显示一些视图。应该可以从代码的几个部分进行调用,所以我决定,将其实现为像这样的特殊结构的静态函数。
工作正常 - 有什么要反对的吗?

struct Appwindows {
  
  static func newWindow(forSpecialView view: SpecialView, title: String = "new Window")
 { let newWindow = newWindowInternal(title: title)!
   
    newWindow.contentView = NSHostingView(rootView: view)
 }
  
  private static func newWindowInternal(title: String = "new Window") -> NSWindow!
 { var newWindow: NSWindow!
   newWindow = NSWindow(
     contentRect: NSRect(x: 20, y: 20, width: 680, height: 600),
     styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
     backing: .buffered,
     defer: false)
     newWindow.center()
     newWindow.isReleasedWhenClosed = false
     newWindow.title = title
     newWindow.makeKeyAndOrderFront(nil)
     return newWindow
 }
}

有没有办法让它更通用,以便可以将任何类型的视图传递给 func?

【问题讨论】:

    标签: swift macos swiftui appkit


    【解决方案1】:

    使您的函数通用并添加视图约束。

    static func newWindow<Content: View>(forSpecialView view: Content, title: String = "new Window") { // <-- Here
    

    另一个很好且简单的解决方案是使用View 扩展。

    extension View {
        private func newWindowInternal(with title: String) -> NSWindow {
            let window = NSWindow(
                contentRect: NSRect(x: 20, y: 20, width: 680, height: 600),
                styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
                backing: .buffered,
                defer: false)
            window.center()
            window.isReleasedWhenClosed = false
            window.title = title
            window.makeKeyAndOrderFront(nil)
            return window
        }
        
        func openNewWindow(with title: String = "new Window") {
            self.newWindowInternal(with: title).contentView = NSHostingView(rootView: self)
        }
    }
    

    用法:

    struct ContentView: View {
        var body: some View {
            Button(action: {
                ContentViewNewWindow().openNewWindow()
            }) {
                Text("Open New Window")
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      相关资源
      最近更新 更多