查找使用 UITapGestureRecognizer 时点击了哪个子视图 [英] Find which child view was tapped when using UITapGestureRecognizer
问题描述
在使用 UIGestureRecognizers 时,我如何知道在哪个子视图上发生了事件?
How do I know on which of the the child views an event occurred when using UIGestureRecognizers?
根据文档:
手势识别器操作触摸到特定视图的命中测试以及该视图的所有子视图.
A gesture recognizer operates on touches hit-tested to a specific view and all of that view’s subviews.
据我所知,'view' 属性是
As far as I can see, the 'view' property is
手势识别器的视图附在.
The view the gesture recognizer is attached to.
这将是父视图.
推荐答案
这将在事件的位置找到最里面的后代视图.(请注意,如果该子视图具有任何交互式内部私有孙子,此代码也会找到它们.)
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];
在 Swift 2 中:
In Swift 2:
let view = gestureRecognizer.view
let loc = gestureRecognizer.locationInView(view)
let subview = view?.hitTest(loc, withEvent: nil) // note: it is a `UIView?`
在 Swift 3 中:
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?`
这篇关于查找使用 UITapGestureRecognizer 时点击了哪个子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!