Skip to content

SwiftUI: conditionally show items in the view

One common thing to do in a form is to have a toggle and when that toggle is enabled, show a bunch of additional options.

You can see this all the time in the Settings app, for example when you enable WiFi.

How can you do that?

First create a Form view with a Toggle control:

struct ContentView: View {
    @State private var enabled = false
    
    var body: some View {
        Form {
            Toggle("Enable?", isOn: $enabled)
        }
    }
}

Then add this block after the Toggle view:

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

like this:

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")
                }
            }
        }
    }
}

Now with the toggle disabled, the Text view will not be visible:

But when you enable the toggle, it appears:


→ Get my Swift Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about swift: