iOS開發 - touchBegan事件判斷點選的位置在View上還是在View的子View上

weixin_34402408發表於2017-08-29

//touch的響應方法

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

CGPointpoint = [[touches anyObject] locationInView:self.view];//convert point to the white layer's coordinates拿到在self.view上但同時在whiteView上的點,下面的同這裡一樣,不一一解釋了

point = [whiteView.layerconvertPoint:point fromLayer:self.view.layer];

//get layer using containsPoint:

if([whiteView.layercontainsPoint: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:nildelegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil] show];

}else{

[[[UIAlertView alloc] initWithTitle:@"Inside White Layer"message:nildelegate:nilcancelButtonTitle:@"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];//    }}

相關文章