Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 340
0-- Avatar asked Jul 15 '14 13:07

0--


2 Answers

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

}
like image 180
gabriel Avatar answered Oct 10 '22 01:10

gabriel


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

like image 25
John Grant Avatar answered Oct 10 '22 01:10

John Grant