在UIScrollView子视图中的UILabels上的UITapGestureRecognizer无法正常工作

Jos*_*son 10 objective-c uiscrollview uilabel uigesturerecognizer ios

我的UIScrollView内容视图中的UILabels上的UITapGestureRecognizer没有调用它的方法.

视图层次结构如下:

  • scrollView(UIScrollView)
    • contentView(UIView)
      • testLabel(UILabel) - 这里是附加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];
Run Code Online (Sandbox Code Playgroud)

这是点击手势识别器应该调用的方法

- (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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我试图触摸UILabel时,从不调用此方法.

我已经尝试将属性canCancelContentTouches设置为滚动视图上的YES和NO,如此线程所示,但它仍然无法正常工作.

奇怪的是,如果我在scrollView之外添加一个UILabel,那么手势识别器就可以了!所以问题只出现在我的contentView中,它是我的scrollView的子视图.

我正在使用自动布局,如果这可能有任何区别?

谢谢!

Wai*_*ain 14

滚动视图还具有手势识别器.默认情况下,任何时候只有一个手势识别器可以处理触摸.你需要让自己成为你的手势的代表,然后实现gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:返回YES.这将允许它与滚动视图同时工作.

  • 是否调用了委托方法?内容视图的大小是什么(记录它)? (2认同)
  • 我的天啊!你说对了!它是`contentView size <UIView: 0xc0345b0; frame = (0 0; 640 0)`,所以它的高度为零!!非常感谢soo soo zoo!!! (2认同)
  • 对于任何阅读本文的人,我遇到了一个引人入胜的晦涩问题。我正在动态生成 UIViewControllers 和它们的视图,并将它们插入到滚动视图中。当然,视图控制器 - 本身 - 在您创建它们时并没有特别保留!视图仍然存在,但 VC 已消失,除非您保留它。 (2认同)