Search code examples
iosswiftevent-handlinguisliderswift4

UISlider doesn't handle .touchUpInside event properly


I have a problem that has been bugging me for the past day and I just can't figure out the solution...

I have an UISlider, which ranges from values 1 to 3 (thats the way we need it to be). The slider is continuous, because it actually updates some properties depending on its current value. Now I want to implement a feature where the slider triggers actions depending on wheather the user is starting to touch it, or ends the touch.

I tried using the .touchDown method to detect the start of touches, which works perfectly. However when I try using .touchUpInside and .touchUpOutside to detect when the user lifts of his / her finger, the event doesn't fire at the appropriate time.

When I drag my finger around the slider, a certain distance from its starting point, the event triggers. But when I just touch it briefly or move it around by a tiny amount, the touchup event doesn't fire at all...

Can someone help me with that? Here is the code I'm using to set up my slider:

let slider: UISlider = {
    let slider = UISlider()
    slider.isContinuous = true
    slider.minimumValue = 1
    slider.maximumValue = 3
    slider.setMinimumTrackImage(#imageLiteral(resourceName: "minimumSliderTrackImage").resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)), for: .normal)
    slider.setMaximumTrackImage(#imageLiteral(resourceName: "maximumSliderTrackImage").resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)), for: .normal)

    let sliderThumb = #imageLiteral(resourceName: "sliderThumbImage")
    slider.setThumbImage(sliderThumb, for: .normal)

    slider.addTarget(self, action: #selector(adjustPriceLabel), for: .valueChanged)
    slider.addTarget(self, action: #selector(handleTouchDown), for: .touchDown)
    slider.addTarget(self, action: #selector(handleTouchUp), for: [.touchUpInside, .touchUpOutside])

    slider.setValue(2.0, animated: true)

    return slider
}()

@objc fileprivate func handleTouchDown() {
    print(1234)
}

@objc fileprivate func handleTouchUp() {
    print(5678)
}

Solution

  • You should try adding .touchCancel state to go to handleTouchUp as well like so:

    slider.addTarget(self, action: #selector(handleTouchUp), for: [.touchUpInside, .touchUpOutside, .touchCancel])