0

我在 UIScrollView 中有 7 个 UIButton。根据代码中的 if 语句,前 3 个 UIButton 可以隐藏或可见。这意味着 3 个 UIButtons 显示有 8 种可能性。我遇到的问题是让 UIScrollView 调整其内容大小,以便其中没有“空”的空间。例如,如果中间的 UIButton 是隐藏的,但它上面和下面的按钮是可见的,则剩下一个空白区域。有什么办法可以让所有按钮在滚动视图中一个在另一个之下而没有任何间隙?

我已经尝试过这段代码,但它没有用:

if([[facilities objectAtIndex:0]intValue] == 1) {

        facilitiesButton.hidden = NO;



    }

    if([[ListingsEnabled objectAtIndex:0]intValue]==1) {

        ListingsBtn.hidden = NO;
    } 

    if([[OffersEnabled objectAtIndex:0]intValue]==1) {

        OffersBtn.hidden = NO;
    }

    CGFloat scrollViewHeight = 0.0f;
    self.DetailScrollView.showsHorizontalScrollIndicator = NO;       
    self.DetailScrollView.showsVerticalScrollIndicator = NO;
    for (UIView* view in self.DetailScrollView.subviews)
    {
        if (!view.hidden)
        {
            CGFloat y = view.frame.origin.y;
            CGFloat h = view.frame.size.height;
            if (y + h > scrollViewHeight)
            {
                scrollViewHeight = h + y;
            }
        }
    }
    self.DetailScrollView.showsHorizontalScrollIndicator = YES;
    self.DetailScrollView.showsVerticalScrollIndicator = YES;

    [self.DetailScrollView setContentSize:(CGSizeMake(self.DetailScrollView.frame.size.width, scrollViewHeight))];
4

1 回答 1

1

正如@Andy 评论的那样,您需要定位实际按钮,而不仅仅是更改滚动视图大小。表格视图可能确实是要走的路,但对于 7 个按钮来说,这可能是矫枉过正。这是一个片段,它将遍历按钮并根据可见性更新它们的位置。我省略了滚动视图,因为它似乎没有必要,但如果您需要在滚动视图中更新它们,我可以编辑代码,请告诉我。

/////////////////////
///// USES ARC //////
/////////////////////

- (void)viewDidLoad
{
    [super viewDidLoad];

    allButtons = [NSMutableArray array];

    // Create 7 buttons and randomly hide some
    for (int i = 0; i < 7; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
        button.frame = CGRectMake(0, 0, 100, 50);
        [button setTitle:[NSString stringWithFormat:@"Button %i", i+1] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(randomizeButtons:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];

        button.hidden = arc4random_uniform(2)-1 > 0;

        [allButtons addObject:button];
    }

    [self updateButtonLayout];
}

-(void)updateButtonLayout
{
    // position buttons based on visiblity

    CGRect lastButtonFrame = CGRectMake(0, 0, 0, 0);
    int verticalPadding = 10;

    for(UIButton *btn in allButtons)
    {
        if(!btn.hidden)
        {
            btn.frame = CGRectMake(lastButtonFrame.origin.x, lastButtonFrame.origin.y+lastButtonFrame.size.height+verticalPadding, btn.frame.size.width, btn.frame.size.height);

            lastButtonFrame = btn.frame;
        }
    }
}

-(void)randomizeButtons:(UIButton *)btn
{
    // Randomize the visiblity of the buttons and update the interface

    for(UIButton *btn in allButtons)
    {
        btn.hidden = arc4random_uniform(2)-1 > 0;
    }

    [self updateButtonLayout];
}
于 2012-08-09T13:52:49.520 回答