Navigation from one screen to another screen in SwiftUI

Ronak Patel
1 min readJul 25, 2022

--

Apple provides two ways to navigate from one screen to another.

  1. Navigation (Push and Pop)
  2. Present and Dismiss

Here, we’ll look Navigation (Push and Pop) ,

Step1. Create one extension for View, This is a generic modifier you can use it multiple times in a view for multiple button navigation.

extension View {/// Navigate to a new view.
/// - Parameters:
/// - view: View to navigate to.
/// - binding: Only navigates when this condition is `true`.
func navigate<NewView: View>(to view: NewView, when binding: Binding<Bool>) -> some View {NavigationView {
ZStack {
self
.navigationBarTitle("")
.navigationBarHidden(true)
NavigationLink(
destination: view
.navigationBarTitle("")
.navigationBarHidden(true),
isActive: binding){
EmptyView()
}
}
}
.navigationViewStyle(.stack)
}
}

Use this View extension as shown,

struct ContentView: View {@State var isSecondScreen : Bool = false
@State var isThirdScreen: Bool = false
@Environment(\.presentationMode) var presentationMode
var body: some View { VStack(alignment: .center){
VStack {
Button(action: {
self.isSecondScreen = true
}){
Text("Goto Second Screen")
.font(.largeTitle)
.fontWeight(.ultraLight)
}
Button(action: {
self.isThirdScreen = true
}) {
Text("Goto Third Screen")
.font(.largeTitle)
.fontWeight(.ultraLight)
}
Button(action: {
//This is used to go back to the previous screen.
presentationMode.wrappedValue.dismiss()
}) {
Text("Goto Previous Screen")
.font(.largeTitle)
.fontWeight(.ultraLight)
}
}
}
.navigate(to: SecondView(), when: $isSecondScreen)
.navigate(to: ThirdView(), when: $isThirdScreen)
}
}

To create a Generic View Modifier, reference is taken from, https://stackoverflow.com/questions/56437335/go-to-a-new-view-using-swiftui

Thanks………..

--

--