How to disable minimum value of 0 in Slider?

313 views Asked by At

I'm working on a watchOS 7 app that uses Slider in SwiftUI. My goal is to allow selection for values 1.0, 2.0, and 3.0. When sliderValues is 1.0, pressing minus button should not change sliderValue to 0.0. How can I disallow selection of value 0.0? Here is a picture to better illustrate the goal:

enter image description here

View file:

import SwiftUI

struct ContentView: View {
    @State private var sliderValue: Double = 1
    
    var body: some View {
        VStack {
            Slider(value: $sliderValue, in: 0...3, step: 1)
            Text("\(sliderValue)")
        }
    }
}
1

There are 1 answers

0
vacawama On BEST ANSWER

Set the range to 1...3. This does make the UI only show 0, 1, or 2 segments.

If you like the look of having 3 segments in the UI, then you can watch the value change with onChange(of:) and set it back to 1 if it goes below 1:

struct ContentView: View {
    @State private var sliderValue: Double = 1
    
    var body: some View {
        VStack {
            Slider(value: $sliderValue, in: 0...3, step: 1)
            .onChange(of: sliderValue) { value in
                if value < 1 {
                    sliderValue = 1
                }
            }
            Text("\(sliderValue)")
        }
    }
}