louallen
louallen

Reputation: 23

UITapGestureRecognizer action not being triggered; userInteractionEnabled already set to YES

My program basically looks like this:

UIViewController -> Custom UIView -> [Array of UIImageView]

My problem is that my recognizer's action method is never called. I've already set the userInteractionEnabled attribute of my UIImageViews to YES.

On my View Controller's viewDidLoad:

- (void)viewDidLoad
{
    NSEnumerator *enumerator = [grid.subviews objectEnumerator];
    UIImageView *view;
    UITapGestureRecognizer *recognizer;

    while((view = [enumerator nextObject])){
        recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openDeal:)];

        view.userInteractionEnabled = YES;
        recognizer.delegate = self;
        recognizer.numberOfTapsRequired = 1;
        [view addGestureRecognizer:recognizer];
        NSLog(@"%d", (int)view.userInteractionEnabled);
        [recognizer release];
    }
    [super viewDidLoad];
}

and openDeal is defined as such:

-(void) openDeal:(UITapGestureRecognizer *) recognizer{
    NSLog(@"%@",[NSString stringWithFormat:@"%d", recognizer.view.tag]);
}

Upvotes: 2

Views: 2169

Answers (4)

18446744073709551615
18446744073709551615

Reputation: 16872

I have just had the same issue.

At first, check the view property. If it is null after addGestureRecognizer, it did not work.

My problem was solved after I removed assignment to the delegate property.

So the code looks like:

{
    UITapGestureRecognizer *bmSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bmSingleTap:)];
    bmSingleTap.numberOfTapsRequired = 1;
    //bmSingleTap.delegate = self;
    [bookmarkTapArea addGestureRecognizer:bmSingleTap];
    NSLog(@"tap: %@ %i", bmSingleTap.view, bmSingleTap.enabled);
}

Edit: By the way, later I wanted to reproduce this bmSingleTap.view==nil effect and could not. Probably, a clean rebuild would do the trick.

Upvotes: 0

AngraX
AngraX

Reputation: 1823

I had the same issue and later found out that I was assigning the same gesture recognizer instance to another view. Gesture recognizers can be associated to a single view only (you can verify that through UIGestureRecognizer's view property).

Make sure you are not reusing your recognizers somewhere else in the code.

Upvotes: 3

Rog
Rog

Reputation: 18670

Your while method looks odd? Are you sure it is running at all?

Try enumerating the subviews array as per below and see if it helps...

NSArray *subviewsArray = grid.subviews;
for (id imageView in subviewsArray)
{
    if ([imageView isKindOfClass:[UIImageView class]])
    {
     // run your code here
    }
}

Upvotes: 0

dasdom
dasdom

Reputation: 14073

First idea: Change your method to:

-(void) openDeal:(UIGestureRecognizer *) recognizer{
    NSLog(@"%@",[NSString stringWithFormat:@"%d", recognizer.view.tag]);
}

Upvotes: 0

Related Questions