10

In my MacOS SwiftUI App I want to display some views in new Windows. The calls shall be possible from several parts of the code so I decided, do implement it as a static func of as special struct like this.
Works fine - there is something to be said against it?

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

Is there a way to make it more generic, so that any kind of views could be passed to the func?

2 Answers 2

14

Make your function generic and add view constraint.

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

Another good and easy solution is to use View extension.

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

Usage:

struct ContentView: View {
    var body: some View {
        Button(action: {
            ContentViewNewWindow().openNewWindow()
        }) {
            Text("Open New Window")
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Xcode 16

Window("What's New", id: "whats-new") {
    Text("New in this version…")
}
struct ContentView: View {
    @Environment(\.openWindow) var openWindow

    var body: some View {
        Button("Show What's New") {
            openWindow(id: "whats-new")
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.