Skip to content

SwiftUI forms: Slider

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.

β†’ Download my free Swift Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about swift: