Last active
January 7, 2023 23:36
-
-
Save johnpatrickmorgan/12e98d244a195a21cda7ea1af1048e9e to your computer and use it in GitHub Desktop.
Unexpected onAppear called when switching out from a NavigationView
This file contains 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
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