Forked from christianselig/sample-view-model-init.swift
Created
May 19, 2024 22:44
-
-
Save ryanashcraft/7e408c3c2b21fb76c359fda60c86c531 to your computer and use it in GitHub Desktop.
manually managing special view's ID
This file contains hidden or 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 | |
@main | |
struct WindowPresentationFunApp: App { | |
@State var appState = AppState() | |
var body: some Scene { | |
WindowGroup { | |
RootView(appState: appState) | |
.onAppear { | |
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { | |
appState.show = true | |
} | |
} | |
} | |
} | |
} | |
struct RootView: View { | |
var appState: AppState | |
var body: some View { | |
ZStack { | |
SpecialView() | |
.id(appState.specialViewID) | |
if appState.show { | |
Text("Some cool text") | |
} | |
} | |
} | |
} | |
struct SpecialView: View { | |
@State var viewModel = ViewModel() | |
var body: some View { | |
Text("Special stuff") | |
} | |
} | |
@Observable class AppState { | |
var show: Bool = false { | |
didSet { | |
specialViewID = UUID() | |
} | |
} | |
var specialViewID = UUID() | |
} | |
@Observable class ViewModel { | |
init() { | |
print("β View model was inited") | |
} | |
deinit { | |
print("β View model was deinited") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By the way, I tested this on macOS with multiple windows. I think you probably want to initialize AppState once per window. Initially I thought all you'd have to do is move AppState to RootView, but that actually didn't have an effect. I followed this tip to initialize it an
onAppear
. It works, but feels like a hacky workaround that shouldn't be necessary. π€·ββοΈ