Introduction
In this article, we will create a simple demo of navigating to different screens using SwiftUI.
If you are new to SwiftUI, please have a look at my article Getting Started with SwiftUI as well.
Pre-requisites
- MacOS
- XCode
Creating a SwiftUI Project to learn about Navigation
So, let's start by creating a SwiftUI Project.
Open XCode -> Select iOS -> App -> Click Next -> Name your project, select Interface as SwiftUI, select Language as Swift -> Save your project to a desired location.


Once you create the project, you will land to the ContentView file which contains the default code of 'Hello World' with a globe image.
Remove all the code inside the 'var body' loop.
Now, let's begin by creating a NavigationStack.
NavigationStack is used to present a stack of views over the main view or root view. We will be adding a NavigationLink inside the NavigationStack to make our screens navigate.
So, let's add NavigationStack inside the body.
struct ContentView: View {
var body: some View {
NavigationStack {
}
}
}
Next, we will be adding NavigationLinks inside the Navigation Stack. Before that, we create some views we will use in our apps to display when the navigation takes place.
In this App, I will be displaying 3 screens when I click on their respective links.
To create a new view, right-click on the Project Name in the Project Navigator -> click on New File -> Click on SwiftUI View under User Interface -> Click Next -> Name the file -> Click on Create.
You can also create a new view by following this step: File -> New -> File -> Click on SwiftUI View under User Interface -> Click Next -> Name the file -> Click on Create.
Following the above steps, I have created 3 files with the names FirstScreenView, SecondScreenView and ThirdScreenView.
Replace the 'Hello World' code with the below code in the respective ScreenView files.
import SwiftUI
struct FirstScreenView: View {
var body: some View {
VStack {
Text("Hello! You are on First Screen")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.yellow)
}
}
struct FirstScreenView_Previews: PreviewProvider {
static var previews: some View {
FirstScreenView()
}
}
import SwiftUI
struct SecondScreenView: View {
var body: some View {
VStack {
Text("Hello! You are on Second Screen")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.green)
}
}
struct SecondScreenView_Previews: PreviewProvider {
static var previews: some View {
SecondScreenView()
}
}









Abhishek TiwariPosted Mar 12, 2024, 9:29 AM
How can I directly navigate from the first screen to the fifth screen? But when i pop it should be in order.