Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Detecting touches in a UIView?

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
like image 663
aryaxt Avatar asked Apr 01 '12 22:04

aryaxt


2 Answers

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))
        {

        }
    }
}
like image 141
aryaxt Avatar answered Nov 03 '22 04:11

aryaxt


this should fix it:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [[event allTouches] anyObject];
    for (UIView* subView in self.subviews) 
    {
        if([subView pointInside:[self convertPoint:touch toView:subView] withEvent:event])
        {
            //do your code here
        }
    }
}
like image 41
skytz Avatar answered Nov 03 '22 06:11

skytz