Expanding on what Mikaela has shown you, here are 3 different methods of transitioning from one screen to another from the “Home Screen” ( ContentView).
Create a test project and replace ContentView with this one:
import SwiftUI
struct ContentView: View {
@State private var isShowingFirstView = false
@State private var isShowingSecondView = false
var body: some View {
NavigationView {
VStack(spacing: 20) {
Text("Navigating from one screen to another")
Button {
// Present a sheet View
isShowingFirstView = true
} label: {
Text("Select First View")
}
Button {
// Present a fullScreenCover View
isShowingSecondView = true
} label: {
Text("Select Second View")
}
// Navigate using a Navigation Link
NavigationLink(destination: ThirdView()) {
Text("Navigation Link to Third View")
}
}
.navigationTitle("Navigation Demo")
.sheet(isPresented: $isShowingFirstView) {
FirstView()
}
.fullScreenCover(isPresented: $isShowingSecondView) {
SecondView(isShowingSecondView: $isShowingSecondView)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Create a SwiftUI file with the name: FirstView and paste this code into it overwriting what is already there.
import SwiftUI
struct FirstView: View {
var body: some View {
ZStack {
Color.yellow
.opacity(0.5)
.ignoresSafeArea()
VStack(spacing: 20) {
Text("First View")
.font(.largeTitle)
Text("Drag down to Dismiss")
}
}
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
Create another SwiftUI file with the name: SecondView and paste this code into it overwriting what is already there.
import SwiftUI
struct SecondView: View {
@Binding var isShowingSecondView: Bool
var body: some View {
ZStack {
Color.green
.opacity(0.5)
.ignoresSafeArea()
VStack(spacing: 20) {
Text("Second View")
.font(.largeTitle)
Button("Tap to Dismiss") {
isShowingSecondView = false
}
}
}
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView(isShowingSecondView: .constant(false))
}
}
Create a third SwiftUI file with the name: ThirdView and paste this code into it overwriting what is already there.
import SwiftUI
struct ThirdView: View {
var body: some View {
ZStack {
Color.red
.opacity(0.5)
.ignoresSafeArea()
VStack(spacing: 20) {
Text("Third View")
.font(.largeTitle)
Text("Tap the < Back button to return.")
}
.navigationTitle("Third View")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct ThirdView_Previews: PreviewProvider {
static var previews: some View {
ThirdView()
}
}