Обработка касания UIImageView

у меня есть представление изображения в качестве фонового изображения. Я ищу, чтобы в каком-то месте при просмотре изображения были включены касания. Я начал с этого:

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

}

Можно ли разрешить пользователю прикасаться к просмотру изображения, когда пользователь касается touchFrame?

Спасибо.


person Streetboy    schedule 02.05.2013    source источник


Ответы (2)


Добавьте UITapGestureRecognizer в UIImageView

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

Теперь в методе HandleGesture:

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

теперь вы можете проверить, находится ли touchedPoint в методе handleGesture в указанной области или нет, и вы можете выполнить желаемую задачу соответственно

person Gaurav Rastogi    schedule 02.05.2013

Вы можете попробовать использовать логическую переменную в качестве члена класса, скажем, BOOL allowTouch, инициализированную значением 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
 }

Это может помочь.

person Amit    schedule 02.05.2013