I have a basic log-in flow on a project I'm working on and wanted to try out the new programmatic navigation in SwiftUI from iOS 16. I noticed that appending to the path array after pressing a Button
for example made transitions behave differently than using a NavigationLink
. This gif illustrates the differences clearer. My theory is the view makes space for the toolbar that appears in the next view and gets redrawn right before it goes offscreen. I'd like some help understanding the differences between these two ways of navigating.
Here is what I have set up regarding the NavigationStack
and the state of the path array within an ObservedObject
.
enum Path {
case welcome
case login
}
class AppState: ObservableObject {
@Published var path: [Path] = []
}
@main
struct MainApp: App {
@ObservedObject var appState = AppState()
var body: some Scene {
WindowGroup {
NavigationStack(path: self.$appState.path) {
// Root View
SplashView()
.navigationDestination(for: Path.self) { path in
switch path {
case .welcome:
WelcomeView()
case .login:
LoginView()
}
}
}
.environmentObject(self.appState)
}
}
}
These are the NavigationLink
/Button
being called from my WelcomeView
:
NavigationLink(value: Path.login) {
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.black)
.frame(maxWidth: .infinity)
.frame(height: 55)
.overlay {
Text("NavigationLink Login")
.font(.custom("Poppins-SemiBold", size: 14))
.foregroundColor(.white)
}
}
Button {
self.appState.path.append(.login)
} label: {
RoundedRectangle(cornerRadius: 10)
.foregroundColor(.black)
.frame(maxWidth: .infinity)
.frame(height: 55)
.overlay {
Text("Button Login")
.font(.custom("Poppins-SemiBold", size: 14))
.foregroundColor(.white)
}
}
Thanks!