Streetboy
Streetboy

Reputation: 4401

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.

Upvotes: 0

Views: 258

Answers (2)

Gaurav Rastogi
Gaurav Rastogi

Reputation: 2145

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

Upvotes: 1

Amit
Amit

Reputation: 1043

You can try having a boolean variable as a class member say BOOL allowTouch initialised with value NO:

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

     if (CGRectContainsPoint(touchFrame, touchLocation)) {
     allowTouch = YES;
     }
 }

 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    if(allowTouch)
     {
      //handle moves here
     }
 }

 -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
     allowTouch = NO;//you can put your condition too to end touches
 }

It may help.

Upvotes: 0

Related Questions