/

SwiftUI: Conditionally Showing Items in a View

SwiftUI: Conditionally Showing Items in a View

In SwiftUI, it is common to have a form with a toggle, where enabling the toggle reveals additional options. This is frequently seen in apps like the Settings app when enabling or disabling features like WiFi. In this blog post, we will explore how to conditionally show items in a view using SwiftUI.

To begin, let’s create a Form view with a Toggle control:

1
2
3
4
5
6
7
8
9
struct ContentView: View {
@State private var enabled = false

var body: some View {
Form {
Toggle("Enable?", isOn: $enabled)
}
}
}

Next, we can add a conditional block of code after the Toggle view to display the desired content when the toggle is enabled:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct ContentView: View {
@State private var enabled = false

var body: some View {
Form {
Toggle("Enable?", isOn: $enabled)

if enabled {
Section {
Text("This appears only if enabled")
}
}
}
}
}

With this implementation, the Text view will only be visible when the toggle is enabled. When the toggle is disabled, the Text view will be hidden.

By utilizing the conditional rendering in SwiftUI, we can dynamically show or hide items in our views based on the state of other controls. This provides a flexible and interactive user interface experience for our users.

Tags: SwiftUI, conditional rendering, toggle, Form view, SwiftUI view components