我在UIScrollView中有7个UIButtons。前3个UIButton可以隐藏或可见,具体取决于代码中的if语句。意思是显示3个UIButton有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))];
答案 0 :(得分: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];
}