NEW: Get your ticket for Hacking with Swift Live 2019! >>

< 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.
  • From and To: The range of the slider.
  • By: 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 var celsius: Double = 0

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

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< 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.4/5

Click here to visit the Hacking with Swift store >>