UITapGestureRecognizer doesn't work added to an UIView?

Víctor B. picture Víctor B. · Mar 30, 2011 · Viewed 10.1k times · Source

I'm triyng to make a gesture recognizer for a simple UIView:

UIView *theView = [[UIView alloc] initWithFrame:rect];
[theView setUserInteractionEnabled:YES];

UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] initWithTarget:self 
                                                                       action:@selector(handleTap)] autorelease];
[theView addGestureRecognizer:tap];

If I debug the property gestureRecognizers of the view it shows the gesture recognizer object. But when I tap inside the view it doesn't work.

The same code using an UIImageView works perfect, any ideas why doesn't work in UIView?

UPDATED:

An example class.

@implementation ExampleClass

- (UIView *)getViewInRect:(CGRect)rect
{
    UIView *theView = [[UIView alloc] initWithRect:rect];
    [theView setUserInteractionEnabled:YES];

    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] 
                                    initWithTarget:self 
                                    action:@selector(handleTap)] 
                                   autorelease];
    [aText addGestureRecognizer:tap];

    return theView;
}

- (UIImageView *)getImageViewInRect:(CGRect)rect
{
    UIImageView *theView = [[UIImageView alloc] initWithRect:rect];
    [theView setUserInteractionEnabled:YES];

    UITapGestureRecognizer *tap = [[[UITapGestureRecognizer alloc] 
                                        initWithTarget:self 
                                                action:@selector(handleTap)] 
                                   autorelease];
    [theView addGestureRecognizer:tap];

    return [theView autorelease];    
}

- (void)handleTap
{
    NSLog(@"Tap Handled!!", nil);
}

@end

UPDATED 2:

Adding UITapGestureRecognizer to all subviews of theView don't fix the problem...

FIX IT!!!

OK!! The problem was the CGRect for theView, it had the width set to 0.0!!!

Answer

Robert Mao picture Robert Mao · Nov 22, 2011

Did you try this?

[view setUserInteractionEnabled:YES];