ios – 取消UIControl animateWithDuration以启动新动画

前端之家收集整理的这篇文章主要介绍了ios – 取消UIControl animateWithDuration以启动新动画前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在创建一个非常简单的方形按钮时遇到以下问题:

>当我将手指放在按钮上时,它应该缩小一点(动画)
>当我用手指按住按钮时,按钮应保持在小状态.
>当我抬起手指时,按钮应该恢复到初始大小(动画).

问题是,当我在播放动画时触摸/抬起按钮应该停止当前动画并缩小/增长.现在我只能在完全播放增长/缩小动画后与按钮交互.

我尝试在触摸功能中使用layer.removeAllAnimations()函数…但没有成功.我试图为View本身和图层添加动画效果.

这是我用来构建自定义按钮的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,animations: { () -> Void in
        self.layer.frame.size.height = 100
        self.layer.frame.size.width = 200
        // I need to adjust the origin here
    },completion: nil)
}

但我认为你可以得到与你提到的App类似的效果

override func touchesBegan(touches: NSSet,animations: { () -> Void in
        self.transform = CGAffineTransformMakeScale(0.6,0.6)
    },completion: nil)

}

    override func touchesEnded(touches: NSSet,animations: { () -> Void in
        self.transform = CGAffineTransformIdentity
    },completion: nil)

}

因为这样它保持了视图的中心.

猜你在找的Xcode相关文章