iOS - Detecting touches in a UIView?

aryaxt picture aryaxt · Apr 2, 2012 · Viewed 20k times · Source

So I have a Subclass of UIView that is suppose to detect touches. The view detect touches only if the touches started inside the current view. When the touches start outside of the view and they move inside my custom view touchesMoved doesn't get called. Any solution to detect moving touches that have not started in the current view?

@implementation MycustomView

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   // This only gets called if touches have started in the current View
} 

@end

Answer

aryaxt picture aryaxt · Apr 2, 2012

The following solution worked. I have multiple instances of MyCustomView; as the touches move I want to detect the views that are being touched

I ended up moving touch detection from MyCustomView to its superView, so the following code is no longer in MyCustomView class:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.contentView];

    for (UIView *view in self.contentView.subviews)
    {
        if ([view isKindOfClass:[MyCustomView class]] &&
            CGRectContainsPoint(view.frame, touchLocation))
        {

        }
    }
}