Search code examples
iosuiimageviewuitouch

UIImageView touch handling


i have an image view as background image. I am seeking that in some place on image view touches would be enabled. I started with this:

- (id)initWithTouchPoint:(CGRect )point
{
    self = [super init];
    if (self) {
        touchFrame = point;
        [self setAccessibilityFrame:touchFrame];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(BOOL)canResignFirstResponder{
    return YES;
}

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

    if (CGRectContainsPoint(touchFrame, touchLocation)) {
        //[self setUserInteractionEnabled:NO];

    }else{
        //[self setUserInteractionEnabled:YES];
    }

    DLog(@"touchesBegan at x : %f y : %f",touchLocation.x,touchLocation.y);
}

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

}

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

}

Is it possible to let user touch over image view when user touches in touchFrame ?

Thank you.


Solution

  • Add UITapGestureRecognizer on UIImageView

    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(handleGesture:)];
    [gesture setNumberOfTapsRequired:1];
    [imageView setUserInteractionEnabled:YES];
    [imageView addGestureRecognizer:gesture];
    

    Now within the HandleGesture Method :

    -(void)handleGesture:(UITapGestureRecognizer *)_gesture
    {
         if (_gesture.state == UIGestureRecognizerStateEnded)
         {
             CGPoint touchedPoint = [_gesture locationInView:self.view];
         }
    }
    

    you can check now wether the touchedPoint within the handleGesture method are in the specified area or not and you can perform your desired task accordingly