Learn how to navigate between screens and apply transitions.
Using NavigationView
and NavigationLink
to create navigation stacks.
NavigationView {
NavigationLink(destination: DetailView()) {
Text("Go to Detail View")
}
.navigationTitle("Home")
}
Explanation:
NavigationView
: Creates a navigation view that manages a navigation stack.NavigationLink(destination: DetailView()) { Text("Go to Detail View") }
: Creates a navigation link that navigates to the DetailView
when tapped..navigationTitle("Home")
: Sets the navigation title to "Home".Passing data to the destination view using NavigationLink
.
struct HomeView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView(data: "Hello, Detail!")) {
Text("Go to Detail View")
}
.navigationTitle("Home")
}
}
}
struct DetailView: View {
let data: String
var body: some View {
Text(data)
}
}
Explanation:
struct HomeView: View
: Defines the home view.NavigationLink(destination: DetailView(data: "Hello, Detail!")) { Text("Go to Detail View") }
: Creates a navigation link that navigates to the DetailView
and passes the string "Hello, Detail!" to it.struct DetailView: View
: Defines the detail view.let data: String
: Declares a property to hold the data passed from the home view.Text(data)
: Displays the data string.Applying custom transitions when showing and hiding views.
@State private var showDetail = false
var body: some View {
VStack {
Button("Show Detail") {
withAnimation {
showDetail.toggle()
}
}
if showDetail {
DetailView()
.transition(.slide)
}
}
}
Explanation:
@State private var showDetail = false
: Declares a state variable to control the visibility of the detail view.Button("Show Detail") { withAnimation { showDetail.toggle() } }
: Toggles the visibility of the detail view with an animation when the button is tapped.if showDetail { DetailView().transition(.slide) }
: Shows the detail view with a slide transition when showDetail
is true.Using TabView
for navigation with tabs.
TabView {
HomeView()
.tabItem {
Label("Home", systemImage: "house")
}
SettingsView()
.tabItem {
Label("Settings", systemImage: "gear")
}
}
Explanation:
TabView
: Creates a tab view that allows navigation between multiple views using tabs.HomeView().tabItem { Label("Home", systemImage: "house") }
: Creates a tab for the home view with a label and system image.SettingsView().tabItem { Label("Settings", systemImage: "gear") }
: Creates a tab for the settings view with a label and system image.