我的UIScrollView内容视图中的UILabels上的UITapGestureRecognizer没有调用它的方法。
视图层次结构如下:
我已将代码简化为示例以突出显示问题
// 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];
这是点击手势识别器应该调用的方法
- (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);
}
}
当我试图触摸UILabel时,从不调用此方法。
我已尝试按照此thread的建议在滚动视图上将属性canCancelContentTouches设置为YES和NO,但它仍无效。
奇怪的是,如果我在scrollView之外添加一个UILabel,那么手势识别器就可以了!所以问题只出现在我的contentView中,它是我的scrollView的子视图。
我正在使用自动布局,如果这可能有什么区别?
谢谢!
答案 0 :(得分:13)
滚动视图还有一个手势识别器。默认情况下,任何时候只有1个手势识别器可以处理触摸。您需要让自己成为手势的代表,然后实施gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:
以返回YES
。这将允许它与滚动视图同时工作。
答案 1 :(得分:2)
将委托添加到tagGestures,
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playSound:)];
singleTap.numberOfTapsRequired = 1;
singleTap.delegate = self;
[testLabel addGestureRecognizer:singleTap];
编辑: -
contentView.userInteractionEnabled = YES;
把这行作为你的代码吧。
答案 2 :(得分:-3)
[yourlabel.addGestureRecognizer:tapGestureDeFromage];
应明确将手势添加到标签中。