Skip to main content

How to create a slider and read values from it

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to create a slider and read values from it 관련

SwiftUI by Example

Back to Home

How to create a slider and read values from it | SwiftUI by Example

How to create a slider and read values from it

Updated for Xcode 15

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. This parameter is optional.

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)
            Text("\(celsius, specifier: "%.1f") Celsius is \(celsius * 9 / 5 + 32, specifier: "%.1f") Fahrenheit")
        }
    }
}

Download this as an Xcode projectopen in new window

A slider with a blue-grey bar and white handle. Below is the text “0.0 Celsius is 32.0 Fahrenheit”.
A slider with a blue-grey bar and white handle. Below is the text “0.0 Celsius is 32.0 Fahrenheit”.
Similar solutions…
How to create a date picker and read values from it | SwiftUI by Example

How to create a date picker and read values from it
How to create a segmented control and read values from it | SwiftUI by Example

How to create a segmented control and read values from it
How to create a picker and read values from it | SwiftUI by Example

How to create a picker and read values from it
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to read the red, green, and blue values from a Color | SwiftUI by Example

How to read the red, green, and blue values from a Color

이찬희 (MarkiiimarK)
Never Stop Learning.