Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Created May 7, 2025 10:21
Show Gist options
  • Save VAndrJ/d6949494bd6c9a458b06c673456db98f to your computer and use it in GitHub Desktop.
Save VAndrJ/d6949494bd6c9a458b06c673456db98f to your computer and use it in GitHub Desktop.
View onAppear example.
//
// 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