How can I programmatically select which WindowGroup to open when the my application is launched? For example:
@main
struct SampleWorkingApp: App
{
var body: some Scene {
WindowGroup(id: "wg1") {
ViewOne()
}
WindowGroup(id: "wg2") {
ViewTwo()
}
}
}
I want to select between wg1
and wg2
depending on a value in UserDefaults.standard
.
The following code produces a compile error, but it shows what I want to do.
@AppStorage("showFirstView") private var showFirstView = true
var body: some Scene {
if showFirstView {
WindowGroup(id: "wg1") {
ViewOne()
}
} else {
WindowGroup(id: "wg2") {
ViewTwo()
}
}
}
Hang on a second... Don't you define a single View inside a WindowGroup? From this page:
// Here's where you define two different WindowGroups
WindowGroup("Message", id: "message", for: UUID.self) { $uuid in
MessageDetail(uuid: uuid)
}
WindowGroup("Account", id: "account-info", for: UUID.self) { $uuid in
AccountDetail(uuid: uuid)
}
// Then, use both the identifier and a value to open the window
struct ActionButtons: View {
var messageID: UUID
var accountID: UUID
@Environment(\.openWindow) private var openWindow
var body: some View {
HStack {
Button("Open message") {
openWindow(id: "message", value: messageID)
}
Button("Edit account information") {
openWindow(id: "account-info", value: accountID)
}
}
}
}
So, you define your different window types, and then open them as required, so your's might be:
var body: some Scene {
WindowGroup(id: "wg1") {
ViewOne()
}
WindowGroup(id: "wg2") {
ViewTwo()
}
}
Then you open a window at startup with:
openWindow(id: showFirstView ? "wg1" : "wg2")