Fork me on GitHub

如何判断touch到子视图或离开视图

这是在ios开发中常见的功能。即,touch移动事件,是移动到当前视图的子视图中,还是移动到当前视图以外了。

办法是,继承UIView,覆盖touchesMoved方法:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch=[touches anyObject]; 
    if (![self pointInside:[touch locationInView:self] withEvent:nil]) { 
        NSLog(@"touches moved outside the view"); 
    }else { 
        UIView *hitView=[self hitTest:[[touches anyObject] locationInView:self] withEvent:nil]; 
        if (hitView==self) { 
            NSLog(@"touches moved in the view"); 
        }else{ 
            NSLog(@"touches moved in the subview"); 
        } 
    } 
}

posted on 2012-02-09 16:49  pengyingh  阅读(284)  评论(0)    收藏  举报

导航