Created
May 7, 2025 10:21
-
-
Save VAndrJ/d6949494bd6c9a458b06c673456db98f to your computer and use it in GitHub Desktop.
View onAppear example.
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
// | |
// MRE.swift | |
// | |
// Created by VAndrJ on 5/7/25. | |
// | |
import SwiftUI | |
struct ContentView: View { | |
@State private var isLogined = false | |
var body: some View { | |
NavigationStack { | |
NavigationLink("Open example", value: 1) | |
.navigationDestination(for: Int.self) { _ in | |
ExampleContainerScreen() | |
} | |
} | |
} | |
} | |
struct ExampleContainerScreen: View { | |
@State private var text = "1" | |
var body: some View { | |
VStack { | |
Button("Add text") { | |
text += "1" | |
} | |
OnAppearExampleView(title: text) | |
} | |
} | |
} | |
struct OnAppearExampleView: View { | |
let title: String | |
@State private var count = 0 | |
init(title: String) { | |
self.title = title | |
print(Self.self, #function, title) | |
} | |
var body: some View { | |
let _ = Self._printChanges() | |
VStack { | |
Text(title) | |
.font(.title) | |
Button("Increment") { | |
count += 1 | |
} | |
Text("\(count)") | |
Text("onAppear should only be called when the View representation on the screen is about to appear, not when the View struct is initialized / re-initialized / body re-evaluated.") | |
} | |
.onAppear { | |
print(Self.self, "onAppear") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment