Search code examples
iosswiftuislider

Move UISlider knob to middle while double tap on it


I want to move the UISlider knob to the middle, or 0.0 value in my case, when the double tap event is occurred on it.

Knob is moving to 0.0 on double tap but immediately it resume to the old position/value.

I have tried the below code. Any help would be much appreciated.

override func viewDidLoad() {

  super.viewDidLoad() 

  let eqSlider = UISlider(frame:CGRectMake(0, 0, 160, 40))
  eqSlider.minimumValue = -12.0
  eqSlider.maximumValue = 12.0
  eqSlider.value = 0.0
  self.view.addSubview(eqSlider)

  // detecting double tap on slider method                
  eqSlider.addTarget(self, action: #selector(EQViewController.doubleTappedSlider(_:event:)), forControlEvents: .TouchDownRepeat)
}

func doubleTappedSlider(sender: UISlider, event: UIEvent) {
  if let firstTouchObj = event.allTouches()?.first {
    if 2 == firstTouchObj.tapCount {
      sender.value = 0.0
    }
  }
}

Solution

  • The problem is that the two taps in your double tap will also be acted upon by the slider itself, so after you set its position manually, the user is setting it straight back.

    To avoid this, you can add the following line after you set the .value:

    sender.cancelTracking(with: nil)
    

    This will "cancel any ongoing tracking" as stated in the documentation.