点击手势动画UIView无法正常工作

我在UILabel上有一个轻击手势,其翻译正在动画。 每当您在动画期间点击标签时,点击手势都没有响应。

这是我的代码:

label.addGestureRecognizer(tapGesture) label.userInteractionEnabled = true label.transform = CGAffineTransformMakeTranslation(0, 0) UIView.animateWithDuration(12, delay: 0, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in label.transform = CGAffineTransformMakeTranslation(0, 900) }, completion: nil) 

手势代码:

 func setUpRecognizers() { tapGesture = UITapGestureRecognizer(target: self, action: "onTap:") } func onTap(sender : AnyObject) { print("Tapped") } 

有任何想法吗? 谢谢 :)

由于一个巨大的原因,你在使用tapgesture之后将无法完成你的目标。 tapgesture与标签的框架相关联。 开始动画时,标签最终帧会立即更改,而您只是在观看假电影(动画)。 如果您能够在屏幕上触摸(0,900),则会在动画发生时正常触发。 有一种方法可以做到这一点有点不同。 最好的方法是使用touchesBegan。 这是我刚刚编写的一个扩展,用于测试我的理论,但可以根据您的需要进行调整。例如,您可以使用实际的子类并访问标签属性而无需循环。

 extension UIViewController{ public override func touchesBegan(touches: Set, withEvent event: UIEvent?) { guard let touch = touches.first else{return} let touchLocation = touch.locationInView(self.view) for subs in self.view.subviews{ guard let ourLabel = subs as? UILabel else{return} print(ourLabel.layer.presentationLayer()) if ourLabel.layer.presentationLayer()!.hitTest(touchLocation) != nil{ print("Touching") UIView.animateWithDuration(0.4, animations: { self.view.backgroundColor = UIColor.redColor() }, completion: { finished in UIView.animateWithDuration(0.4, animations: { self.view.backgroundColor = UIColor.whiteColor() }, completion: { finished in }) }) } } } } 

你可以看到它正在测试CALayer.presentationLayer()的坐标。这就是我所说的电影。 说实话,我仍然没有完全围绕表示层及其工作原理。

如果要查看动画,则需要将其放在onTap处理程序中。

 let gesture = UITapGestureRecognizer(target: self, action: "onTap:") gesture.numberOfTapsRequired = 1 label.addGestureRecognizer(gesture) label.userInteractionEnabled = true label.transform = CGAffineTransformMakeTranslation(0, 0) UIView.animateWithDuration(12, delay: 3, options: [.AllowUserInteraction], animations: { () -> Void in label.transform = CGAffineTransformMakeTranslation(0, 900) }, completion: nil) func onTap(sender : AnyObject) { print("Tapped") } 

要使您的点击手势起作用,您必须设置点击次数。 添加此行:

tapGesture.numberOfTapsRequired = 1

(我假设tapGesture与你称之为label.addGestureRecognizer(tapGesture)那个相同)

以下是基于Swift 3中@ agibson007的答案的更通用的答案。

这并没有立即解决我的问题,因为我有其他子视图覆盖了我的观点。 如果遇到问题,请尝试更改扩展类型并为touchLocation编写print语句以找出函数何时触发。 接受的答案中的描述很好地解释了这个问题。

 extension UIViewController { open override func touchesBegan(_ touches: Set, with event: UIEvent?) { guard let touch = touches.first else { return } let touchLocation = touch.location(in: self.view) for subview in self.view.subviews { if subview.tag == VIEW_TAG_HERE && subview.layer.presentation()?.hitTest(touchLocation) != nil { print("[UIViewController] View Touched!") // Handle Action Here } } } }