点击手势动画UIView无法正常工作
问题描述:
我对UILabel的翻译正在进行动画处理。每当您在动画中点击标签时,轻按手势都没有响应。点击手势动画UIView无法正常工作
这里是我的代码:
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之后的一大理由。该抽头与标签的框架相关联。开始动画时,标签的最终框架会立即更改,而您只是在观看假影片(动画)。如果您能够在屏幕上触摸(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(坐标)..这就是我一直在呼唤电影。说实话,我仍然没有完全围绕表示层和它的工作原理。
答
如果你想看到动画,你需要把它放在处理器的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")
}
答
下面是斯威夫特3
基于答案来自@ agibson007一个更通用的答案这并没有马上解决我的问题,因为我有额外的子视图覆盖我的看法。如果遇到问题,请尝试更改扩展类型并编写touchLocation
的打印语句以查明函数何时触发。接受答案中的描述很好地解释了这个问题。
extension UIViewController {
open override func touchesBegan(_ touches: Set<UITouch>, 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
}
}
}
}
也许这将帮助你http://*.com/questions/26210318/tap-gesture-with-uigesturerecognizerstate-not-working – owlswipe
显示您双击手势初始化代码。 – sschale
@sschale编辑 – mlevi