使用滑动手势swift更改UISlider值

时间:2016-09-11 04:58:33

标签: ios swift uigesturerecognizer uislider

我有一个带滑动手势的UIView。

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

当我尝试更改它的值时,但值从0跳到20.我希望值在刷卡时连续变化。我该怎么做?

3 个答案:

答案 0 :(得分:5)

从您的代码判断,看起来您正试图进行“上下颠簸”。在屏幕上转换为UISlider值更改。

正如其他人已经提到的,首先要将您的UISwipeGestureRecognizer更改为UIPanGestureRecognizer

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

然后在您的平移功能中,您需要根据用户平移的数量更新滑块值。

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

只需调整tolerance变量即可让用户更多/更少地滑动以调整滑块值。

答案 1 :(得分:0)

您不想要UISwipeGestureRecognizer,而是想要UIPanGestureRecognizer。滑动是一次性手势。

Apple's documentation说“滑动是一种离散的手势,因此每个手势只会发送一次关联的动作消息。”

答案 2 :(得分:0)

您可以将手势识别器的主要操作设置为代码(您可以使用界面构建器)

@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
    if recognizer.state == UIGestureRecognizerState.Began {
    } else if recognizer.state == UIGestureRecognizerState.Ended {
    } else if recognizer.state == UIGestureRecognizerState.Changed {
    }
}
祝你好运! =]