-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
- 1
- 1
此方法用到的频率还是很高的,但是有一种情况,如下图:
同时有白色蓝色两个视图,蓝色为白色视图的子视图,两个视图都有各自点击的事件,怎么来判断我点击的是哪个,你可以使用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];
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
//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];
// }
}