mle*_*evi 6 iphone uiview ios uitapgesturerecognizer 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)
Run Code Online (Sandbox Code Playgroud)
手势代码:
func setUpRecognizers() {
tapGesture = UITapGestureRecognizer(target: self, action: "onTap:")
}
func onTap(sender : AnyObject) {
print("Tapped")
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢 :)
这些天这很容易,你只需覆盖hitTest。
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let pf = layer.presentation()!.frame
// note, that is in the space of our superview
let p = self.convert(point, to: superview!)
if pf.contains(p) { return self }
return nil
}
Run Code Online (Sandbox Code Playgroud)
相关提示——
不要忘记,在大多数情况下,如果动画正在运行,您当然会想要取消它。因此,假设有一个“移动目标”,并且您希望能够用手指抓住它并将其滑动到其他地方,在这种情况下,您的视图控制器中的代码自然看起来像 ..
func sliderTouched() {
if alreadyMoving {
yourPropertyAnimator?.stopAnimation(true)
yourPropertyAnimator = nil
}
etc ...
}
Run Code Online (Sandbox Code Playgroud)
使用点击手势后,您将无法完成现在的任务,原因有一个。点击手势与标签的框架相关联。当动画开始时,标签最终帧会立即更改,而您只是在观看一部假电影(动画)。如果您能够触摸屏幕上的 (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
})
})
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以看到它正在测试 CALayer.presentationLayer() 的坐标。这就是我所说的电影。老实说,我还没有完全理解表示层及其工作原理。
| 归档时间: |
|
| 查看次数: |
5733 次 |
| 最近记录: |