NEW: Learn SwiftUI with my free YouTube video series! >>

< How to create secure text fields using SecureField   How to create a picker and read values from it >

How to create a slider and read values from it

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 wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< How to create secure text fields using SecureField   How to create a picker and read values from it >
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 me know!

Average rating: 4.6/5

Click here to visit the Hacking with Swift store >>