iOS UIButton在UIScrollView中无法点击

iOS UIButton can't click in UIScrollView

我之前搜索过一些 post。但是我试不出正确的结果。

我生成更多按钮并在 UIScrollView 中添加视图。

我已经在 storybaord 中设置了关于视图和滚动视图的自动布局。

但是按钮点击不是监听器。不知道为什么。

我设置了

 _sclVW.delaysContentTouches = NO;
[_sclVW setCanCancelContentTouches:NO];
_sclVW.userInteractionEnabled = YES;

但是按钮还是点不进去

我的代码如下:

     _sclVW.delegate = self;

    _sclVW.delaysContentTouches = NO;
    [_sclVW setCanCancelContentTouches:NO];
    _sclVW.userInteractionEnabled = YES;


    int btnWidth = 80,btnHigh=50;
    for( int i = 0 ; i < 50 ; i++ )
    {

        UIButton *button  =[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button addTarget:self action:@selector(btnSendTag:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
        button.tag = i;
        button.titleLabel.numberOfLines = 0;
        button.titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.userInteractionEnabled = YES;
        [button setEnabled:YES];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor darkGrayColor]];

        if( i < 3)
        {
            button.frame = CGRectMake( i *(btnWidth +  20),  0 , 80,50 );
        }
        else
        {
            button.frame = CGRectMake( (i%3) *(btnWidth +  20), (i/3) *(btnHigh + 20)  , 80,50 );

        }
        [_contentVW addSubview:button];

    }
}

-(void) btnSendTag:(UIButton *)sender
{
    NSLog(@"btn click:%li",(long)sender.tag);
}

有人知道如何解决这个问题吗?

非常感谢。

我在 github(this code).

中有 post 我的简单测试项目

我从示例项目中发现了您的问题。这里的问题是 Storyboard 中 contentVW 的高度和宽度是 0。因此该视图的子视图(按钮)无法与用户交互。

看下图:

在这里您可以看到 UIScrollView 的子视图对于 widthheight 具有值 0

所以更改 widthheight 视图,就像滚动视图一样,这样您就可以点击这些按钮了。