使用UIPanGestureRecognizer向下滑动UIView

时间:2018-01-13 02:40:59

标签: ios uiview uipangesturerecognizer

我的IBActionUIPanGestureRecognizerUIView,我能够处理手势并识别状态变化从开始,取消和结束,以及回复那些变化。

但是,当使用sender.location处理向下滑动时,UIView实际上会在手势开始后向上移动,然后继续向下移动。经验很刺耳,我不确定我做错了什么。有人有什么想法吗?

func update(_ translation: CGPoint, origin: CGPoint) {

    let offSetY = translation.y

    cardView.frame.origin.y = offSetY

    let multiplier = 1 - (translation.y / 2000)
    self.view.alpha = multiplier
}


func cancel(_ origin: CGPoint) {

    let animator = UIViewPropertyAnimator(duration: 0.6, dampingRatio: 0.6) {
        self.visualEffectView.alpha = 1
        self.cardView.alpha = 1.0
        self.view.alpha = 1.0
        self.cardView.center = origin
    }
    animator.startAnimation()
}

func finish() {
    let animator = UIViewPropertyAnimator(duration: 0.9, dampingRatio: 0.9) {
        self.visualEffectView.effect = nil
        self.dismiss(animated: true, completion: nil)
    }
    animator.startAnimation()
}



@IBAction func panGestureAction(_ sender: UIPanGestureRecognizer) {

    self.view.backgroundColor = .white
    let originalCardPosition = cardView.center

   //let cardOriginY = cardView.frame.origin.y
    let translation = sender.translation(in: self.cardView)
    let origin = sender.location(in: self.cardView)

        switch sender.state {
        case .changed:


            if translation.y > 0 { update(translation, origin: origin) }

        case .ended:

            let translation = sender.translation(in: self.cardView)

            if translation.y > 100 {

                finish()

            } else {
                cardView.alpha = 1.0
                cancel(originalCardPosition)

            }
        case .cancelled:
            cancel(originalCardPosition)

        default: break
        }

}

1 个答案:

答案 0 :(得分:1)

问题是您将origin.y的{​​{1}}直接设置为cardView的值。您需要将translation.y添加到手势开始时确定的视图原始translation.y值。

向班级添加属性:

y

然后在手势的var originalY: CGFloat = 0 状态下,设置它:

.began

然后在originalY = cardView.frame.origin.y 方法中设置原点:

update