不废话,直接上代码
self.back = [[UIView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 100.0f, 100.0F)]; self.back.backgroundColor = [UIColor redColor]; [self.window addSubview:self.back]; UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 200, 40)]; [btn addTarget:self action:@selector(zouni) forControlEvents:UIControlEventTouchUpInside]; btn.backgroundColor = [UIColor blackColor]; [self.back addSubview:btn];
效果如下
红色的方块是back,在这个范围内的btn可以点,点了 - (void)zouni
是有反应的,外边的没反应。
求解释,求原理,还有什么办法可以让整个btn可以点?
创建一个UIView的子类,并且重写这个子类的
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
方法,在这个方法里,判断point参数是否在你的btn的范围内,如果是,则返回btn
红框外的事件传递给了白view
解决办法:扩大父view范围
范围外不接受事件