我的解决方案来自Bannings大神的“iOS 为移动动画中的View添加touch事件”,下面是地址
http://blog.csdn.net/zhangao0086/article/details/38356691
我功力不够。。。就只好把他的代码直接搬了过来XD
class ViewController: UIViewController {
var testLayer = CALayer()
var testView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
func initView() {
testlayer.anchorPoint = CGPointMake(0, 0)
testlayer.bounds = CGRectMake(100, 100, 100, 100)
testlayer.backgroundColor = UIColor.greenColor().CGColor
testView.frame = testlayer.bounds
self.view.addSubview(testView)
self.testView.layer.addSublayer(testlayer)
let animation = CAKeyframeAnimation(keyPath: "position")
//起始值和末尾值
animation.values = [NSValue(CGPoint: CGPointMake(0, 0)),NSValue(CGPoint: CGPointMake(320, 640))]
//动画持续的时间
animation.duration = 4.0
animation.delegate = self
//animation.autoreverses = true//自动复位
self.testlayer.addAnimation(animation, forKey: "move")
let tap = UITapGestureRecognizer(target: self, action: "testtap:")
self.view.addGestureRecognizer(tap)
}
func testtap(click:UITapGestureRecognizer) {
let point = click.locationInView(self.testView)
if ((self.testlayer.presentationLayer()?.hitTest(point)) != nil) {
print("tap me")
}
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
print("anim end")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
运行代码后,我们可以看到有一个绿色的小方块会进行你设定的起点和终点进行缓慢移动,当你点击这个小方块时,控制台会输出“tap me”,当动画结束后,控制台会输出“anim end”。
现在,我们已经可以获取得到运动中的动画的点击事件以及动画结束后发出的广播,那么,我们就写出琴键点击和游戏结束的判断了。