Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

ios - Tap Gesture on animating UIView not working

I have a tap gesture on a UILabel who's translation is being animated. Whenever you tap on the label during the animation there's no response from the tap gesture.

Here's my code:

    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)

Gesture code:

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

Any ideas? Thanks :)


Note added for 2021:

These days this is dead easy, you just override hitTest.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How to detect touches in a view which is moving

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
}

It's that easy

Related tip -

Don't forget that in most cases if an animation is running, you will, of course, almost certainly want to cancel it. So, say there's a "moving target" and you want to be able to grab it with your finger and slide it somewhere else, naturally in that use case your code in your view controller will look something like ..

   func sliderTouched() {
       if alreadyMoving {
          yourPropertyAnimator?.stopAnimation(true)
          yourPropertyAnimator = nil
       }
       etc ...
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...