Search code examples
iosuitouch

iOS cancel touch events in certain regions


Is there a way to cancel touch events in certain regions of a view? I have a custom UIView and I only want to process touch events only if they are say 100 pixels from the edges of the screen.


Solution

  • As Justin said, add a custom UIView in interface builder (or programmatically) and add it to the view. let's call that view touchArea. Then in your Viewcontroller.m file, implement the

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

    methods (depends on what you're trying to do), and in these do:

        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInView:self.view];
    if (CGRectContainsPoint(touchArea.frame, location)) {
    
    //code to execute
    
    }
    

    actually, I think even a CGRect as an instance variable that is placed on the view can work, but the above is how I achieved it.