Go to a new view in SwiftUI
This SwiftUI tutorial will help you to learn to navigate to a new view in SwiftUI. We’ll be accomplishing this using the Navigation view and Navigation link. It will send the user to a new view.
What this blog will cover:
- how to use the navigation link
- how to create a new view
Syntax:
NavigationLink(destination: DestinationViewName)
- destination: the name of the new view.
Now, First of all, let’s see how we can create a new SwiftUI file.
Go to the file option in your Xcode, and from there create a new SwiftUI file, and save it as “NewView”. Now there are two view files in your project which are ContentView and NewView
Xcode -> File -> New -> File -> SwiftUI View
After creating a new SwiftUI file, Add a NavigationView in your main view, “Content View”.
struct ContentView: View {
var body: some View {
NavigationView{
//NavigationLink will go here
}.padding()
}
}
}
- NavigationView: We use it for navigating or moving to different views of our application.
The navigation links to the new View will go into the NavigationView we just created.
struct ContentView: View {
var body: some View {
NavigationView{
NavigationLink(destination: newView()){
Text("Navigate to newView")
}.padding()
}
}
}- NavigationLink: It’s used for describing which view we want our application to show.
We can also use modifiers for modifying our link to look more like a clickable button.
struct ContentView: View {
var body: some View {
NavigationView{
NavigationLink(destination: newView()){
Text("Navigate to newView")
.foregroundColor(Color.white)
.frame(width: 300,height: 70)
.background(Color.blue)
.cornerRadius(35)
.font(.system(size: 20))
}.padding()
}
}
}- Text: it’s the text that is given to the link
- ForegroundColor: It’s the color of the text
Here is given the complete SwiftUI Code for your reference:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView{
NavigationLink(destination: newView()){
Text("Navigate to newView")
.foregroundColor(Color.white)
.frame(width: 300,height: 70)
.background(Color.blue)
.cornerRadius(35)
.font(.system(size: 20))
}.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Leave a Reply