Skip to content

Instantly share code, notes, and snippets.

@johnpatrickmorgan
Last active January 7, 2023 23:36
Show Gist options
  • Save johnpatrickmorgan/12e98d244a195a21cda7ea1af1048e9e to your computer and use it in GitHub Desktop.
Save johnpatrickmorgan/12e98d244a195a21cda7ea1af1048e9e to your computer and use it in GitHub Desktop.
Unexpected onAppear called when switching out from a NavigationView
import SwiftUI
/*
Navigating through to LoggedInView prints the following:
WelcomeView
LogInFormView
LoggedInView
WelcomeView -> Why is this view's onAppear called when it's not on screen??
*/
struct ContentView: View {
@State var isLoggedIn = false
var body: some View {
if isLoggedIn {
LoggedInView(logOut: { isLoggedIn = false })
} else {
NavigationView {
WelcomeView(logIn: { isLoggedIn = true })
}
}
}
}
struct WelcomeView: View {
var logIn: () -> Void
var body: some View {
NavigationLink(destination: LogInFormView(logIn: logIn), label: { Text("Go to form") })
.onAppear { print("\(Self.self)") }
}
}
struct LogInFormView: View {
var logIn: () -> Void
var body: some View {
Button("Log in", action: logIn)
.onAppear { print("\(Self.self)") }
}
}
struct LoggedInView: View {
var logOut: () -> Void
var body: some View {
Button("Log out", action: logOut)
.onAppear { print("\(Self.self)") }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment