Search code examples
sliderswiftui

Setting the value of a SwiftUI slider by tapping on it


How can I change the value of a SwiftUI Slider by tapping on it?


Solution

  • Here's a minimal implementation I created using a GeometryReader that rounds to the closest value:

    struct TappableSlider: View {
        var value: Binding<Float>
        var range: ClosedRange<Float>
        var step: Float
    
        var body: some View {
            GeometryReader { geometry in
                Slider(value: self.value, in: self.range, step: self.step)
                    .gesture(DragGesture(minimumDistance: 0).onEnded { value in
                        let percent = min(max(0, Float(value.location.x / geometry.size.width * 1)), 1)
                        let newValue = self.range.lowerBound + round(percent * (self.range.upperBound - self.range.lowerBound))
                        self.value.wrappedValue = newValue
                    })
            }
        }
    }
    

    which can be used just like a normal slider, e.g.

    TappableSlider(value: $sliderValue, in: 1...7, step: 1.0)