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
422 views
in Technique[技术] by (71.8m points)

objective c - Find which child view was tapped when using UITapGestureRecognizer

How do I know on which of the the child views an event occurred when using UIGestureRecognizers?

According to the documentation:

A gesture recognizer operates on touches hit-tested to a specific view and all of that view’s subviews.

As far as I can see, the 'view' property is

The view the gesture recognizer is attached to.

which will be the parent view.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This will find the innermost descendant view at the event's location. (Note that if that child view has any interactive internal private grandchildren this code will find those too.)

UIView* view = gestureRecognizer.view;
CGPoint loc = [gestureRecognizer locationInView:view];
UIView* subview = [view hitTest:loc withEvent:nil];

In Swift 2:

let view = gestureRecognizer.view
let loc = gestureRecognizer.locationInView(view)
let subview = view?.hitTest(loc, withEvent: nil) // note: it is a `UIView?`

In Swift 3:

let view = gestureRecognizer.view
let loc = gestureRecognizer.location(in: view)
let subview = view?.hitTest(loc, with: nil) // note: it is a `UIView?`

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

2.1m questions

2.1m answers

60 comments

56.9k users

...