Getting Started
Conditional rendering allows you to show and hide views easily by using if-statements or Switch Statements.
Displaying Views with Conditional Rendering
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.
Else and Else-Ifs
Conditional rendering with if statements work similarly to regular if statements. You can also add else or else-if clauses.
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.
Using Switch Statements
A simpler, more elegant approach is using Switch Statements.
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.
In These Collections
This article can also be found in these collections.