UIScrollView子视图并不总是可点击的

时间:2013-03-13 19:21:51

标签: objective-c uiscrollview uibutton touch addsubview

我正在向UIScrollView添加子视图。对于这个问题,我简化了添加的视图:testView它包含UIButton

我的滚动视图效果很好,但按钮上的触摸效果不佳

  • 我可以点击第一个按钮,但仅限于(近似)100个第一个像素
  • 滚动效果非常好。
  • 我无法点击第一个按钮的结尾
  • 我无法点击其他按钮

这是我的代码:

__block CGFloat scrollViewContentSize = 0;
__block CGFloat buttonRectOrigineY = 0;

[self.itemsToDisplay enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    CGRect frameTest = CGRectMake(0, buttonRectOrigineY/2, 320, 200);
    UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    testButton.frame = frameTest;
    UIView *testView = [[UIView alloc] initWithFrame:frameTest];
    [testView addSubview:testButton];
    [self.articleScrollView addSubview:testView];
    buttonRectOrigineY      += 200;
    scrollViewContentSize   += 200;
}];
[self.articleScrollView setContentSize:CGSizeMake(320, scrollViewContentSize)];

这里是图像,以便很好地理解我的问题: uiscrollview with button not touchable

2 个答案:

答案 0 :(得分:0)

您可以使用bringSubviewToFront来避免此问题

CGRect frameTest = CGRectMake(0, buttonRectOrigineY/2, 320, 200);
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
testButton.frame = frameTest;
UIView *testView = [[UIView alloc] initWithFrame:frameTest];
[testView addSubview:testButton];
[testView bringSubviewToFront:testButton];
[self.articleScrollView addSubview:testView];
[self.articleScrollView bringSubviewToFront:testView];

如果您再次遇到问题,请在按钮周围应用边框并检查手动显示的按钮区域。

答案 1 :(得分:0)

我误认为我的按钮和视图的框架。这是一个可以帮助任何人的工作代码。

__block CGFloat scrollViewContentSize = 0;
__block CGFloat buttonRectOrigineY = 0;

[self.itemsToDisplay enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    CGRect frameTestButton = CGRectMake(0, 0, 300, 150);
    CGRect frameTestView = CGRectMake(10, buttonRectOrigineY, 300, 200);
    UIButton *testButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    testButton.frame = frameTestButton;
    testButton.backgroundColor = [UIColor greenColor];
    UIView *testView = [[UIView alloc] initWithFrame:frameTestView];
    if(idx == 0)
        testView.backgroundColor = [UIColor yellowColor];
    if(idx == 1)
        testView.backgroundColor = [UIColor orangeColor];
    if(idx == 2)
        testView.backgroundColor = [UIColor redColor];
    if(idx == 3)
        testView.backgroundColor = [UIColor magentaColor];
    if(idx == 4)
        testView.backgroundColor = [UIColor purpleColor];
    if(idx <= 4){
        LogDebug(@"idx : %lu", (unsigned long)idx);
        [testView addSubview:testButton];
        [self.articleScrollView addSubview:testView];
        [self.articleScrollView bringSubviewToFront:testView];
        buttonRectOrigineY      += 200;
        scrollViewContentSize   += 200;
    }
}];
[self.articleScrollView setContentSize:CGSizeMake(320, scrollViewContentSize)];