Kerby Jean Kerby Jean - 2 months ago 36
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
view.addGestureRecognizer(swipeUpGesture)

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

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:))) 
view.addGestureRecognizer(pan)

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.

Comments