注意:通過storyBoard或xib創建的視圖 , initwithFrame方法不會被執行,需要使用- (void)awakeFromNib;
1 - (void)awakeFromNib 2 { 3 4 RedView *view1 = [[RedView alloc]initWithFrame:CGRectMake(20, 210, 280, 40)]; 5 [self addSubview:view1]; 6 self.redView = view1; 7 8 BlueView *view2 = [[BlueView alloc]initWithFrame:CGRectMake(60, 130, 200, 200)]; 9 [self addSubview:view2];10 [view2 setAlpha:0.5];11 self.blueView = view2;12 13 GreenView *view3 = [[GreenView alloc]initWithFrame:CGRectMake(80, 150, 160, 160)];14 [self addSubview:view3];15 [view3 setAlpha:0.5];16 self.greenView = view3;17 18 }
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
重寫hittext方法,攔截用戶觸摸視圖的順序
hitTest方法的都用是由window來負責觸發的。
如果希望用戶按下屏幕 , 就立刻做出響應 , 使用touchesBegin
如果希望用戶離開屏幕 , 就立刻做出響應 , 使用touchesEnd
通常情況下使用touchesBegin,以防止用戶認為點擊了沒有反應。
把hitTest的點轉換為 redView的點,使用convertPoint: toView;
CGPoint redP = [self convertPoint:point toView:self.redView];
判斷一個點是否在視圖的內部:
if ([self.greenView pointInside:greenP withEvent:event]) {
return self.greenView;
}
1 -(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event 2 { 3 //1.判斷當前視圖是否能接受用戶響應 4 /*self.UserInteractionEnabled=YES 5 self.alpha > 0.01; 6 self.hidden = no; 7 */ 8 //2.遍歷其中的所有的子視圖,能否對用戶觸摸做出相應的響應 9 //3.把event交給上級視圖活上級視圖控制器處理10 //4.return nil;如果返回nil,說明當前視圖及其子視圖均不對用戶觸摸做出反應。11 /*12 參數說明:13 point:參數是用戶觸摸位置相對于當前視圖坐標系的點;14 注視:以下兩個是聯動使用的,以遞歸的方式判斷具體響應用戶事件的子視圖15 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;16 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;17 這兩個方法僅在攔截觸摸事件時使用,他會打斷響應者鏈條,平時不要調用。18 提醒:如果沒有萬不得已的情況,最好不要自己重寫hitTest方法;19 */20 CGPoint redP = [self convertPoint:point toView:self.redView];21 //轉換綠色視圖的點22 CGPoint greenP = [self convertPoint:point toView:self.greenView];23 //pointInside 使用指定視圖中的坐標點來判斷是否在視圖內部,最好不要在日常開發中都用。24 if ([self.greenView pointInside:greenP withEvent:event]) {25 return self.greenView;26 }27 NSLog(@"%@",NSStringFromCGPoint(redP));28 if ([self.redView pointInside:redP withEvent:event]) {30 return self.redView;31 }33 return [super hitTest:point withEvent:event];34 }
代碼在:https://github.com/zhangjinling/IOSPRogects/tree/master/%E6%89%8B%E5%8A%BF/03.%E8%A7%A6%E6%91%B8%E4%BA%8B%E4%BB%B6%E6%8B%A6%E6%88%AA
新聞熱點
疑難解答