为什么" RemoveAllAnimations()"不停止我的动画?

时间:2015-02-09 04:34:33

标签: ios animation

我有一个非常简单的示例,允许拖动UIView。触摸时,我会在拖动方向上产生惯性效果一秒钟。如果我再次触地,我需要停止所有惯性动画并开始做另一次拖动。这是我的代码,“clearAllAnimations”不会停止我的动画。我怎么能实现呢?

import UIKit

class ViewController: UIViewController {
    var tile : UIView = UIView()
    var labelView = UITextView()
    var displayLink : CADisplayLink?

    override func viewDidLoad() {
        super.viewDidLoad()

        tile.frame = CGRect(x: 0, y: 0, width: 256, height: 256)
        tile.backgroundColor = UIColor.redColor()
        view.addSubview(tile)

        var panGesture = UIPanGestureRecognizer(target: self, action: Selector("panHandler:"))
        view.addGestureRecognizer(panGesture)

        labelView.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: 44)
        labelView.backgroundColor = UIColor.clearColor()
        view.addSubview(labelView)
    }

    func panHandler (p: UIPanGestureRecognizer!) {
        var translation = p.translationInView(view)
        if (p.state == UIGestureRecognizerState.Began) {
            self.tile.layer.removeAllAnimations()
        }
        else if (p.state == UIGestureRecognizerState.Changed) {
            var offsetX = translation.x
            var offsetY = translation.y

            var newLeft = tile.frame.minX + offsetX
            var newTop = tile.frame.minY + offsetY

            self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height)
            labelView.text = "x: \(newLeft); y: \(newTop)"
            p.setTranslation(CGPoint.zeroPoint, inView: view)
        }
        else if (p.state == UIGestureRecognizerState.Ended) {
            var inertia = p.velocityInView(view)
            var offsetX = inertia.x * 0.2
            var offsetY = inertia.y * 0.2
            var newLeft = tile.frame.minX + offsetX
            var newTop = tile.frame.minY + offsetY

            UIView.animateWithDuration(1, delay: 0, options:UIViewAnimationOptions.CurveEaseOut, animations: {_ in
                self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height)
                }, completion: nil)

        }
    }
}

1 个答案:

答案 0 :(得分:1)

设置UIViewAnimationOptions.AllowUserInteraction可以解决问题。启动动画的新代码是:

UIView.animateWithDuration(animationDuration, delay: 0, options:UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.BeginFromCurrentState, animations: {_ in
            self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height)
            }, completion: nil)