当状态改变时,UILongPressGestureRecognizer会跟进动画

时间:2016-02-16 10:37:25

标签: ios swift animation

我在UIImageView上添加了UILongPressGestureRecognizer。它的目的是如果用户按下图像,动画应该开始。这是完美的。但是一旦用户移动他的手指,动画就会停止。我知道这是因为状态发生了变化。然而,我想继续动画,并且只有当用户从图像中移开他的手指时停止。

到目前为止,我添加手势识别器的代码是

let tapGestureRecognizer = UILongPressGestureRecognizer(target:self, action:Selector("imageTapped:"))
    tapGestureRecognizer.minimumPressDuration = 0
    barcodeImage.userInteractionEnabled = true
    barcodeImage.addGestureRecognizer(tapGestureRecognizer)

并且动画的代码是

func imageTapped(gesture: UILongPressGestureRecognizer)
{
    let animation : CATransition  = CATransition()
    animation.delegate = self
    animation.duration = 2.5
    animation.repeatCount = Float.infinity
    animation.type = "rippleEffect"
    if(gesture.state == UIGestureRecognizerState.Ended){
        logger.log("press ended");
        // and stop animation
        barcodeImage.layer.removeAllAnimations()
    }else{
        logger.log("show animation")
        barcodeImage.layer.addAnimation(animation, forKey: nil)
    }
}

状态改变后如何继续播放动画?

2 个答案:

答案 0 :(得分:0)

barcodeImage.userInteractionEnabled = true
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if (touches.first?.view == barcodeImage) {
        print("show animation")
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("removeAllAnimations")
}

override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
    print("removeAllAnimations")
}

答案 1 :(得分:0)

改为使用UIPanGestureRecognizer,

let tapGestureRecognizer = UIPanGestureRecognizer(target:self, action:Selector("imageTapped:"))
barcodeImage.userInteractionEnabled = true
barcodeImage.addGestureRecognizer(tapGestureRecognizer)

func imageTapped(gesture: UILongPressGestureRecognizer)
{
    switch gesture.state {
    case .Began :
        let animation : CATransition  = CATransition()
        animation.delegate = self
        animation.duration = 2.5
        animation.repeatCount = Float.infinity
        animation.type = "rippleEffect"
        barcodeImage.layer.addAnimation(animation, forKey: nil)
        break;
    case .Ended, .Cancelled :
        barcodeImage.layer.removeAllAnimations()
        break;
    default :
        break
   }

}