Skip to content

Instantly share code, notes, and snippets.

@trozware
Last active April 29, 2022 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trozware/bce6a2c3a35b04de0c29470de7442ab2 to your computer and use it in GitHub Desktop.
Save trozware/bce6a2c3a35b04de0c29470de7442ab2 to your computer and use it in GitHub Desktop.
Open a view in another window - SwiftUI for Mac
import SwiftUI
struct ContentView: View {
var body: some View {
Button("Open Secondary Window") {
openSecond()
}
.frame(width: 400, height: 150)
}
// open the sub view in a new window
func openSecond() {
// create a hosting controller to hold the SwiftUI view
let hostingController = NSHostingController(rootView: SubWindowView())
// create a window to hold the hosting controller & set its title
let window = NSWindow(contentViewController: hostingController)
window.title = "Secondary Window"
// create a window controller to own the window
let controller = NSWindowController(window: window)
// tell the controller to show the window
controller.showWindow(nil)
}
}
struct SubWindowView: View {
// you must set a frame for the secondary window here
// this uses width & height, but you'll probably want to use the full frame modifier
var body: some View {
Text("This is the sub window view.")
.frame(width: 200, height: 150)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment