通过点击来设置SwiftUI滑块的值

时间:2019-11-04 04:42:38

标签: slider swiftui

如何通过轻按来更改SwiftUI Slider的值?

1 个答案:

答案 0 :(得分:1)

这是我使用GeometryReader创建的最小化实现,该值四舍五入到最接近的值:

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
                })
        }
    }
}

可以像普通滑块一样使用,例如

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