Last active
April 29, 2022 05:11
-
-
Save trozware/bce6a2c3a35b04de0c29470de7442ab2 to your computer and use it in GitHub Desktop.
Open a view in another window - SwiftUI for Mac
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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