Alex Rivera | Logout

UITapGestureRecognizer on UILabels in subview of UIScrollView not working

Asked 2013-07-18T10:38:23.770
12

I have a problem where my UITapGestureRecognizer on my UILabels in a content view in my UIScrollView is not calling it's methods.

The view hierarchy is as follows:

  • scrollView (UIScrollView)
    • contentView (UIView)
      • testLabel (UILabel) - here is where the UITapGestureRecognizer is attached

I have distilled the code down to an example to highlight the problem

// Set scrollview size - Added in Storyboad
[scrollView setContentSize:CGSizeMake([arrayOfVerbs count]*self.view.frame.size.width, scrollView.contentSize.height)];
[scrollView setCanCancelContentTouches:YES]; // Tried both yes and no
[scrollView setPagingEnabled:YES];

// Add content view
UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height)];
[scrollView addSubview:contentView];

// Add test UILabel
UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
[testLabel setBackgroundColor:[UIColor redColor]];
[testLabel setText:@"Test touch"];
[testLabel setUserInteractionEnabled:YES];
[contentView addSubview:testLabel];

// Add gesture recogniser
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playSound:)];
singleTap.numberOfTapsRequired = 1;
[testLabel addGestureRecognizer:singleTap];

And this is the method that the tap gesture recogniser should call

- (void)playSound:(UITapGestureRecognizer *)sender {

    NSLog(@"play sound");

    if(sender.state == UIGestureRecognizerStateEnded)
    {
        int pronounNumber = [sender.view tag];
        int exampleNumber = (int)sender.view.frame.origin.x%(int)self.view.frame.size.width;

        NSLog(@"Pronoun is %i and example is %i", pronounNumber, exampleNumber);
    }
}

This method is never called when I tried to touch on the UILabel.

I have tried setting the p

Edit
Report

1 Answer

2

Add delegate to tagGestures,

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playSound:)];
singleTap.numberOfTapsRequired = 1;
singleTap.delegate = self;
[testLabel addGestureRecognizer:singleTap];

EDIT:-

contentView.userInteractionEnabled = YES;

put this line your code it'l work.

answered 2013-07-18T10:40:36.073

Your Answer