取消 UIControl animateWithDuration 开始新的动画

Cancel UIControl animateWithDuration to start a new animation

我在创建具有以下行为的非常简单的方形按钮时遇到了麻烦:

问题是,当我在播放动画时 touch/lift 起来时,按钮应该停止当前动画并且 shrink/grow。现在我只能在 grow/shrink 动画完全播放后才能与按钮交互。

我尝试在触摸功能中使用 layer.removeAllAnimations() 功能……但没有成功。我尝试为视图本身和图层设置动画。

这是我对用于构建自定义按钮的 UIControl 的尝试。

import UIKit

class TriggerPad: UIControl {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(frame: CGRect) {
        //  I init the Frame with w:200 h:100 in my ViewController
        super.init(frame: frame)

        self.backgroundColor = UIColor.clearColor()

        self.layer.frame = frame
        self.layer.backgroundColor = UIColor.blueColor().CGColor
        self.multipleTouchEnabled = true
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

        let oldFrame = self.layer.frame
        self.layer.removeAllAnimations()

        UIView.animateWithDuration(2) { () -> Void in
            self.layer.frame.size.height = 50
            self.layer.frame.size.width = 100
            // I need to adjust the origin here
        }
    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

        let oldFrame = self.layer.frame
        self.layer.removeAllAnimations()

        UIView.animateWithDuration(2) { () -> Void in
            self.layer.frame.size.height = 100
            self.layer.frame.size.width = 200
            // I need to adjust the origin here
        }
    }
}

你可以解决它添加到 UIView 的动画选项 .AllowUserInteraction。您的代码将是:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
        self.layer.frame.size.height = 50
        self.layer.frame.size.width = 100
        // I need to adjust the origin here
    }, completion: nil)
}

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
        self.layer.frame.size.height = 100
        self.layer.frame.size.width = 200
        // I need to adjust the origin here
    }, completion: nil)
}

但我认为您可以获得与您提到的应用类似的效果:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
        self.transform = CGAffineTransformMakeScale(0.6, 0.6)
    }, completion: nil)

}

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

    UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
        self.transform = CGAffineTransformIdentity
    }, completion: nil)

}

因为这样可以保持视图的中心。