Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ryanashcraft/7e408c3c2b21fb76c359fda60c86c531 to your computer and use it in GitHub Desktop.

Select an option

Save ryanashcraft/7e408c3c2b21fb76c359fda60c86c531 to your computer and use it in GitHub Desktop.

Revisions

  1. ryanashcraft revised this gist May 19, 2024. 1 changed file with 13 additions and 6 deletions.
    19 changes: 13 additions & 6 deletions sample-view-model-init.swift
    Original 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
    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")
    }
  2. @christianselig christianselig created this gist May 19, 2024.
    53 changes: 53 additions & 0 deletions sample-view-model-init.swift
    Original 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")
    }
    }