Skip to content

SwiftUI forms: Slider

New Course Coming Soon:

Get Really Good at Git

The Slider form control in SwiftUI lets us create a bar that the user can swipe left or right to decrease or increase its value.

We initialize a Slider by setting 3 parameters: value, in, step:

@State private var age: Double = 0

//...

Slider(value: $age, in: 0...100, step: 1)

in limits the minimum and maximum values we can use.

step means we can step by a value of 1 at a time, in this case we can go from 0 to 1 to 2 etc. You could use 10, or 0.2, and so on.

Since Slider takes a Double value, by default we increment the decimals too.

Example:

struct ContentView: View {
    @State private var age: Double = 0
    
    var body: some View {
        Form {
            Slider(value: $age, in: 0...100, step: 1)
            Text("\(age)")
        }
    }
}

Notice how I added a Text view to show the value of age.

Since it’s a double, we have lots of decimals.

We could format that, but for this we’ll have another post.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Swift Handbook

Here is how can I help you: