0--
0--

Reputation: 221

How to implement a tap and hold on an UIImageView?

I'm trying to call an alert box when I touch and hold down an image for 2 seconds. Here's what I got so far:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UILongPressGestureRecognizer *tapAndHoldGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapAndHoldGesture:)];
    tapAndHoldGesture.minimumPressDuration = 0.1;
    tapAndHoldGesture.allowableMovement = 600;
    [self.view addGestureRecognizer:tapAndHoldGesture]; 
}

- (void) handleTapAndHoldGesture:(UILongPressGestureRecognizer *)gestureRecognizer{
    if (gestureRecognizer.state != UIGestureRecognizerStateEnded) {
        return;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Gesture:" message:@"hold it" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

Not sure if this effects anything, but the Image View is programmatically created later and not on load. Thank you in advance as any help is appreciated..

Also, I've looked at the following links:

Long press gesture on UICollectionViewCell

Long press gesture recognizer on UIButton?

Apple Link 1

Apple Link 2

Upvotes: 6

Views: 4709

Answers (2)

gabriel
gabriel

Reputation: 2359

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self setupGesture];
}

-(void) setupGesture
{
    UILongPressGestureRecognizer *lpHandler = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleHoldGesture:)];
    lpHandler.minimumPressDuration = 1; //seconds
    lpHandler.delegate = self;
    //myUIImageViewInstance - replace for your instance/variable name
    [**myUIImageViewInstance** addGestureRecognizer:lpHandler];
}

- (void) handleHoldGesture:(UILongPressGestureRecognizer *)gesture
{
   if(UIGestureRecognizerStateBegan == gesture.state)
   {
        // Called on start of gesture, do work here
   }

   if(UIGestureRecognizerStateChanged == gesture.state)
   {
        // Do repeated work here (repeats continuously) while finger is down
   }

   if(UIGestureRecognizerStateEnded == gesture.state)
   {
        // Do end work here when finger is lifted
   }

}

Upvotes: 8

John Grant
John Grant

Reputation: 1679

UIImageViews by default have userInteractionEnabled = NO. If you're adding your gesture recognizer to an instance of UIImageView, make sure you set it back to YES: myImageView.userInteractionEnabled = YES

Upvotes: 4

Related Questions