Navigating SwiftUI views
Navigation in mobile apps was always a critical issue. UIKit supported navigation from day one, and SwiftUI launched with essential support from NavigationView.
Navigation in SwiftUI is quite different than UIKit. While in UIKit, we had to create a new view controller and push it to a stack using UINavigationController, in SwiftUI, it works slightly differently.
Remember we discussed declarative programming earlier in this chapter? This is how navigation works in SwiftUI. Instead of creating and pushing a new view, we use the state to present sheets, modals, and links to navigate to a new view.
Let’s see how to present a modal view using state modification in SwiftUI:
struct ContentView: View { @State var isModalPresented = false
var body: some View {
VStack {
Button("Present...