我需要一个项目中所有按钮的缩放弹簧动画。 所以我将UIButton子类化并覆盖触摸事件函数。
import UIKit
class UIAnimatedButton: UIButton {
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.transform = CGAffineTransformMakeScale(0.8, 0.8)
})
super.touchesBegan(touches, withEvent: event)
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: { () -> Void in
self.transform = CGAffineTransformIdentity
}) { (Bool) -> Void in
super.touchesCancelled(touches, withEvent: event)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: UIViewAnimationOptions.AllowUserInteraction,
animations: { () -> Void in
self.transform = CGAffineTransformIdentity
}) { (Bool) -> Void in
super.touchesEnded(touches, withEvent: event)
}
}
}
这在快速拍摄中效果很好但是当我长按(1-2秒)触摸按钮时,我不会在内部动作事件中进行修饰。 当我把它切换回普通的UIButton时,一切正常。
为什么会发生这种情况?
答案 0 :(得分:6)
而不是在touchesCancelled
和touchesEnded
方法的完成块中调用super,而是在那里调用self.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
。
答案 1 :(得分:0)
不确定到底是为什么,但是您需要在动画外调用super.touchesEnded(touches, with: event)
所以(迅速5)
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.2,
initialSpringVelocity: 6.0,
options: UIView.AnimationOptions.allowUserInteraction,
animations: { () -> Void in
self.transform = CGAffineTransform.identity
}) { (Bool) -> Void in
}
super.touchesEnded(touches, with: event)
}