NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to create a slider and read values from it

Paul Hudson    @twostraws   

Fully updated for Xcode 11 GM

SwiftUI’s Slider view works much like UISlider, although you need to bind it somewhere so you can store its value.

When you create it there are a variety of parameters you can provide, but the ones you probably care about most are:

  • Value: What Double to bind it to.
  • In: The range of the slider.
  • Step: How much to change the value when you move the slider.

For example, this code creates a slider bound to a Celsius property, then updates a text view as the slider moves so that it converts between Celsius and Fahrenheit:

struct ContentView: View {
    @State private var celsius: Double = 0

    var body: some View {
        VStack {
            Slider(value: $celsius, in: -100...100, step: 0.1)
            Text("\(celsius) Celsius is \(celsius * 9 / 5 + 32) Fahrenheit")
        }
    }
}

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Similar solutions…

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5