iOS开发 – touchBegan事件判断点击的位置在View上还是在View的子View上

释放双眼,带上耳机,听听看~!
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

此方法用到的频率还是很高的,但是有一种情况,如下图:
这里写图片描述
同时有白色蓝色两个视图,蓝色为白色视图的子视图,两个视图都有各自点击的事件,怎么来判断我点击的是哪个,你可以使用Tap的手势来写,通过tap.view.tag来区分是哪个view,还有一种办法就是利用touch方法来解决,实现的效果如下:
这里写图片描述

来看看代码是怎么写的:

//给出两个view,不多解释了
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor=[UIColor grayColor];
whiteView=[[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
whiteView.center=self.view.center;
whiteView.backgroundColor=[UIColor whiteColor];
[self.view addSubview:whiteView];
blueLayer=[CALayer layer];
blueLayer.frame=CGRectMake(50, 50, 100, 100);
blueLayer.backgroundColor=[UIColor blueColor].CGColor;
[whiteView.layer addSublayer:blueLayer];
}

 

//touch的响应方法
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CGPoint point = [[touches anyObject] locationInView:self.view];
//convert point to the white layer's coordinates拿到在self.view上但同时在whiteView上的点,下面的同这里一样,不一一解释了
point = [whiteView.layer convertPoint:point fromLayer:self.view.layer]; //get layer using containsPoint:
if ([whiteView.layer containsPoint:point]) {
//convert point to blueLayer’s coordinates
point = [blueLayer convertPoint:point fromLayer:whiteView.layer];
if ([blueLayer containsPoint:point])
{
[[[UIAlertView alloc] initWithTitle:@"Inside Blue Layer"
message:nil
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
else
{
[[[UIAlertView alloc] initWithTitle:@"Inside White Layer"
message:nil
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil]show];
}
}
//----------华丽丽的分割线,从这里开始是我写的点击的方法,相对来说比上面使用起来更方便点
//    CGPoint point=[[touches anyObject]locationInView:self.view];
//    CALayer *layer=[whiteView.layer hitTest:point];
//    if (layer==whiteView.layer) {
//        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"" message:@"Inside white layer" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
//        [alertView show];
//    }
//    else if (layer==blueLayer){
//        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"" message:@"Inside blue layer" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
//        [alertView show];
//    }
}

人已赞赏
iOS文章

IOS [__NSCFConstantString size]: unrecognized selector sent to instance 错误

2020-3-30 3:48:55

iOS文章

IOS UILabel中的文字吸顶(顶部对齐)

2020-3-30 5:03:12

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索