一赏迟、系統(tǒng)是怎么找到第一響應(yīng)者的惰拱?? --只通過UIView及其子類查找
0 調(diào)用根視圖的hitTtest:withEvent淮逊,其的執(zhí)行過程如下:
Ie calls pointInside:withEvent:of self
If the return is NO,? hitTest:withEvent:? returns? nil . the end of the story.
If the return is YES, it sends? hitTest:withEvent:? messages to its subviews. it starts from the top-level subview, and continues to other views until a subview returns a non- nil? object, or all subviews receive the message.
If a subview returns a non- nil? object in the first time, the first? hitTest:withEvent:? returns that object. the end of the story.
If no subview returns a non- nil? object, the first? hitTest:withEvent:? returns? self
三袱耽、hitTest:withEvent應(yīng)用:
1)父視圖中有布局重疊的且都可響應(yīng)用戶操作的對象咒循,如:ScrollView and Button据途,如果Button在ScrollView下面,正常情況下Button是不會成為第一響應(yīng)者的叙甸,如果想讓Button可以響應(yīng)在其布局內(nèi)的觸摸事件颖医,可以在Button和ScrollView的父View中重寫hitTest:withEvent方法
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
CGPoint hitPoint = [_testButton convertPoint:point fromView:self];
if ([_testButton pointInside:hitPoint withEvent:event])
? ? ? ? return _testButton;
return [super hitTest:point withEvent:event];
}//_testButton是指定響應(yīng)對象的 弱 引用
參考: 這里
2)UIView的子類不響應(yīng)觸摸事件,但其子View可以響應(yīng)裆蒸。通過設(shè)置userInteractionEnabled=NO熔萧,可以使UIView子類不響應(yīng)觸摸事件,但其會挾持子View僚祷,原因見3)
這時佛致,可以通過重寫hitTest:withEvent來實現(xiàn):
-(id)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
id hitView = [super hitTest:point withEvent:event];
if (hitView == self) return nil;
else return hitView;
}
參考: 這里
3) userInteractionEnabled = NO的作用:使當(dāng)前的hitTest:withEvent返回nil,其它的類似屬性還有:Hidden=Y(jié)ES辙谜,alpha<0.01俺榆,(UIControl中Enabled=NO?装哆?)罐脊,事件發(fā)生的點在子View的幾何范圍內(nèi)定嗓,卻超過了父View的幾何范圍( clipsToBounds=NO時可出現(xiàn)此種情況 )