小编典典

在动画UIView上点击手势不起作用

swift

我在正在翻译动画的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")
}

有任何想法吗?谢谢 :)


阅读 517

收藏
2020-07-07

共1个答案

小编典典

使用Tapgesture后,您将无法完成自己的工作,原因有1个。手势与标签的框架相关联。开始动画时,标签的最后一帧立即更改,而您只是在观看假电影(动画)。如果您能够触摸屏幕上的(0,900),它将在发生动画时照常触发。不过,有一种方法可以使此方法有所不同。最好的办法是使用touchesBegan。这是我刚刚编写的用于检验理论的扩展,但可以进行扩展以适合您的需求,例如,您可以使用实际的子类并访问标签属性而无需循环。

extension UIViewController{

public override func touchesBegan(touches: Set<UITouch>, 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()的坐标。这就是我所说的电影。老实说,我还没有完全围绕表示层及其工作原理进行研究。

2020-07-07