4

我有这个小示例应用程序,它创建了我的 SwiftUI MacOS 应用程序的多个 Windows。
是否可以:

  • 在 MainView 中列出所有打开的窗口?
  • 从 MainView 关闭单个窗口?
  • 从MainView 向单个窗口发送消息?
@main
struct MultiWindowApp: App {
  @State var gvm = GlobalViewModel()
  var body: some Scene {
    WindowGroup {
      MainView()
      .environmentObject(gvm)
    }
    WindowGroup("Secondary") {
      SecondaryView(bgColor: .blue)
      .environmentObject(gvm)
    }
    .handlesExternalEvents(matching: Set(arrayLiteral: "*"))
  }
}


struct MainView: View {
  @Environment(\.openURL) var openURL
  @EnvironmentObject var vm : GlobalViewModel

  var body: some View {
    VStack {
      Text("MainView")
      Button("Open Secondary") {
        if let url = URL(string: "OpenNewWindowApp://bla") {
          openURL(url)
        }
       //List of all open Windows
          // Button to close a single window
          // Button to set color of  a single window to red
      }
    }
    .padding()
  }
}

struct SecondaryView: View {
  var bgColor : Color

  @EnvironmentObject var vm : GlobalViewModel

  var body: some View {
    VStack{
      Spacer()
      Text("Viewer")
      Text("ViewModel: \(vm.name)")
      Button("Set VM"){
        vm.name = "Tom"
      }
      Spacer()
    }
    .background(bgColor)
    .frame(minWidth: 300, minHeight: 300, idealHeight: 400, maxHeight: .infinity, alignment: .center )
  }
}

class GlobalViewModel :ObservableObject {
  @Published var name = "Frank"
}

4

1 回答 1

4

有可能有一种更以 SwiftUI 为中心的方式来执行此操作。如果还没有,我当然希望 Apple 为 Mac 方面添加一些更好的窗口管理功能——现在,一切看起来都像是一个黑客。

这是我想出的:


@main
struct MultiWindowApp: App {
  @State var gvm = GlobalViewModel()
  var body: some Scene {
    WindowGroup {
      MainView()
      .environmentObject(gvm)
    }
    WindowGroup("Secondary") {
      SecondaryView(bgColor: .blue)
      .environmentObject(gvm)
    }
    .handlesExternalEvents(matching: Set(arrayLiteral: "*"))
  }
}


struct MainView: View {
  @Environment(\.openURL) var openURL
  @EnvironmentObject var vm : GlobalViewModel

  var body: some View {
    VStack {
      Text("MainView")
        List {
            ForEach(Array(vm.windows), id: \.windowNumber) { window in
                HStack {
                    Text("Window: \(window.windowNumber)")
                    Button("Red") {
                        vm.setColor(.red, forWindowNumber: window.windowNumber)
                    }
                    Button("Close") {
                        window.close()
                    }
                }
                
            }
        }
      Button("Open Secondary") {
        if let url = URL(string: "OpenNewWindowApp://bla") {
          openURL(url)
        }
      }
    }
    .padding()
    .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

struct SecondaryView: View {
  var bgColor : Color
  @EnvironmentObject var vm : GlobalViewModel

    @State private var windowNumber = -1
    
  var body: some View {
    VStack{
        HostingWindowFinder { window in
            if let window = window {
                vm.addWindow(window: window)
                self.windowNumber = window.windowNumber
            }
        }
      Spacer()
      Text("Viewer")
      Text("ViewModel: \(vm.name)")
      Button("Set VM"){
        vm.name = "Tom"
      }
      Spacer()
    }
    .background(vm.backgroundColors[windowNumber] ?? bgColor)
    .frame(minWidth: 300, minHeight: 300, idealHeight: 400, maxHeight: .infinity, alignment: .center )
  }
}

class GlobalViewModel : NSObject, ObservableObject {
    @Published var name = "Frank"
    @Published var windows = Set<NSWindow>()
    @Published var backgroundColors : [Int:Color] = [:]
    
    func addWindow(window: NSWindow) {
        window.delegate = self
        windows.insert(window)
    }
    
    func setColor(_ color: Color, forWindowNumber windowNumber: Int) {
        backgroundColors[windowNumber] = color
    }
}

extension GlobalViewModel : NSWindowDelegate {
    func windowWillClose(_ notification: Notification) {
        if let window = notification.object as? NSWindow {
            windows = windows.filter { $0.windowNumber != window.windowNumber }
        }
    }
}

struct HostingWindowFinder: NSViewRepresentable {
    var callback: (NSWindow?) -> ()

    func makeNSView(context: Self.Context) -> NSView {
        let view = NSView()
        DispatchQueue.main.async { [weak view] in
            self.callback(view?.window)
        }
        return view
    }
    func updateNSView(_ nsView: NSView, context: Context) {}
}

我正在使用来自https://lostmoa.com/blog/ReadingTheCurrentWindowInANewSwiftUILifecycleApp/的技巧来获取对NSWindow. 它以集合的形式存储在视图模型中。稍后,要访问诸如关闭窗口之类的东西。我通过windowNumber.

当一个窗口出现时,它会将自己添加到视图模型的窗口列表中。然后,当视图模型作为委托获得windowWillClose调用时,它会将其从列表中删除。

设置背景颜色是通过backgroundColors视图模型上的属性完成的。如果没有一组,它使用传入的背景颜色属性。您可以选择多种不同的方式来构建这个位。

于 2021-02-06T21:02:16.820 回答