Kerby Jean Kerby Jean - 1 year ago 149
Swift Question

Change UISlider value with swipe gesture swift

I have a UIView with a swipe gesture .

let swipeUpGesture = UISwipeGestureRecognizer(target: self, action: #selector(NextStepCaptureVC.handleSwipeUp(gesture:)))
swipeUpGesture.direction = .up

func handleSwipeUp(gesture: UISwipeGestureRecognizer) {
print("Swipe Up")
heightSlider.setValue(20, animated: true)

When I try to change the value it works but the value jump from 0 to 20. I want the value to change continuously while swiping. How can I do it?

Answer Source

Judging from your code, it looks like you are trying to make 'panning up and down' on the screen translate to the UISlider value changing.

As already mentioned by others, first thing is to change your UISwipeGestureRecognizer to a UIPanGestureRecognizer

let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(gesture:))) 

Then in your pan function, you need to update the slider value based on how much the user has panned.

func pan(gesture: UIPanGestureRecognizer) {
    // The amount of movement up/down since last change in slider
    let yTranslation = gesture.translation(in: gesture.view).y

    // The slide distance needed to equal one value in the slider
    let tolerance: CGFloat = 5

    if abs(yTranslation) >= tolerance {
        let newValue = heightSlider.value + Float(yTranslation / tolerance)
        heightSlider.setValue(newValue, animated: true)

        // Reset the overall translation within the view
        gesture.setTranslation(.zero, in: gesture.view)

Simply adjust the tolerance variable to make the user swipe more/less in order to adjust the slider value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download