Getting Started
Conditional rendering allows you to show and hide views easily by using if-statements or Switch Statements.
Displaying Views with Conditional Rendering
struct ContentView: View {
@State private var counter = 0
var body: some View {
VStack {
Text("\(counter) cookies eaten")
Button("Eat another cookie!") {
counter = counter + 1
}
if counter > 10 {
Text("Maybe you should stop.")
}
}
}
}
In the code snippet above, the Text saying "Maybe you should stop" appears when the counter is greater than 10. Conditional rendering refers to the if statement that controls whether or not the Text appears.
if counter > 10 {
Text("Maybe you should stop.")
}
Else and Else-Ifs
Conditional rendering with if statements work similarly to regular if statements. You can also add else or else-if clauses.
if counter > 10 {
Text("Maybe you should stop.")
} else if counter == 3 {
Text("You've eaten my favourite number of cookies")
} else {
Text("Keep eating cookies!")
}
Using Conditional Rendering to Manage App States
The same concept of conditional rendering can be used to switch out entire views.
Using If Statements
In the following example, an if statement is used with else if clauses to swap out views easily. The appState
State variable is passed as a Binding into the other screens, allowing them to set the variable and switch to another screen.
struct ContentView: View {
@State private var appState = 0
var body: some View {
if appState == 0 {
HomeView(appState: $appState)
} else if appState == 1 {
WelcomeView(appState: $appState)
} else if appState == 2 {
LogInView(appState: $appState)
}
}
}
Using Switch Statements
A simpler, more elegant approach is using Switch Statements.
struct ContentView: View {
@State private var appState = 0
var body: some View {
switch appState {
case 0:
HomeView(appState: $appState)
case 1:
WelcomeView(appState: $appState)
case 2:
LogInView(appState: $appState)
default:
EmptyView()
}
}
}
Using Switch Statements and Enumeration
To make it even more readable, the Int
can be replaced with a custom enumeration. Enumerations allow you to define different options.
In the following example, an enumeration, AppState
is defined with 3 cases—home, welcome, and log in. Like with the examples above, the enumeration value is passed as a Binding into the other screens.
enum AppState {
case home
case welcome
case logIn
}
struct ContentView: View {
@State private var appState: AppState = .home
var body: some View {
switch appState {
case .home:
HomeView(appState: $appState)
case .welcome:
WelcomeView(appState: $appState)
case .logIn:
LogInView(appState: $appState)
}
}
}
struct WelcomeView: View {
@Binding var appState: AppState
var body: some View {
VStack {
Text("Welcome to my amazing app!")
.font(.largeTitle)
Button("Log In") {
appState = .logIn
}
}
}
}