Tob*_*idt 4 xcode core-animation ios swift
我在创建一个非常简单的方形按钮时遇到以下问题:
当我将手指放在按钮上时,它会缩小一点(动画)
当我用手指按住按钮时,按钮应保持在小状态.
当我抬起手指时,按钮应该恢复到初始大小(动画).
问题是,当我在播放动画时触摸/抬起按钮应该停止当前动画并缩小/增长.现在我只能在完全播放增长/缩小动画后与按钮交互.
我尝试在触摸功能中使用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
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以解决它添加到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)
}
Run Code Online (Sandbox Code Playgroud)
但我认为你可以得到与你提到的App类似的效果:
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)
}
Run Code Online (Sandbox Code Playgroud)
因为这样它保持了视图的中心.