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.
Revisions
-
ryanashcraft revised this gist
May 19, 2024 . 1 changed file with 13 additions and 6 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -3,7 +3,7 @@ import SwiftUI @main struct WindowPresentationFunApp: App { @State var appState = AppState() var body: some Scene { WindowGroup { RootView(appState: appState) @@ -18,11 +18,12 @@ struct WindowPresentationFunApp: App { struct RootView: View { var appState: AppState var body: some View { ZStack { SpecialView() .id(appState.specialViewID) if appState.show { Text("Some cool text") } @@ -32,21 +33,27 @@ struct RootView: View { 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") } -
christianselig created this gist
May 19, 2024 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,53 @@ 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() 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 } @Observable class ViewModel { init() { print("✅ View model was inited") } deinit { print("❌ View model was deinited") } }