TD540
TD540

Reputation: 1760

make Slider value adjustable only one way

Is it possible to make a SwiftUI Slider only go one way? For example: only to increase the value to the right.

import SwiftUI
struct ContentView: View {
    @State private var sliderValue = 0.0
    var body: some View {
        VStack {
            Text(sliderValue.description)
            Slider(value: $sliderValue)
        }
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In my app, sliderValue may only be adjusted to increase, never decrease

Upvotes: 1

Views: 164

Answers (1)

swiftPunk
swiftPunk

Reputation: 1

Yes, you can but you should use custom Binding!

import SwiftUI

struct ContentView: View {
    
    @State private var sliderValue = 0.0
    
    var body: some View {
        
        VStack {
            
            Text(sliderValue.description)
            
            Slider(value: Binding.init(get: { () -> Double in return sliderValue },
                                       set: { (newValue) in if (newValue > sliderValue) { sliderValue = newValue } }))
            
        }
        
    }
}

Upvotes: 3

Related Questions