【发布时间】:2014-08-29 16:58:49
【问题描述】:
尝试做一些相当简单的事情。我正在创建一行矩形,它们放置在水平滚动的UIScrollView 中。矩形布局完美。但是,每个矩形上都有一个UILabel。仅显示第一个标签。其他都不是。这里的红色矩形是基本的CGRects。黄色是让我调试标签是否绘制正确。如您所见,仅显示第一个标签:
self.dayButtonsArray = [[NSMutableArray alloc] initWithCapacity:21];
CGFloat buttonSpacing = 2.0f;
CGFloat buttonWidth = 50.0f;
CGFloat buttonHeight = self.contentView.frame.size.height;
CGFloat startX = self.contentView.frame.origin.x;
CGFloat thisX = startX;
for (int i=0; i<21; i++) {
CGRect frame = CGRectMake(thisX, self.contentView.frame.origin.y, buttonWidth, buttonHeight);
UIView *thisButton = [[UIView alloc] initWithFrame:frame];
// set up a label for each view
UILabel *label = [[UILabel alloc] initWithFrame:frame];
[label setTextColor:[UIColor blackColor]];
label.font = [UIFont fontWithName:DEFAULT_FONT size:14];
label.textAlignment = NSTextAlignmentCenter;
[label setText:[NSString stringWithFormat:@"DAY %d", i+1]];
[labelsArray addObject:label];
[thisButton setBackgroundColor:[UIColor redColor]];
// now add these elements
[thisButton addSubview:label];
[thisButton bringSubviewToFront:label];
[self.contentView addSubview:thisButton];
[self.contentView bringSubviewToFront:thisButton];
[self.dayButtonsArray addObject:thisButton];
CGRect contentSize = self.contentView.frame;
contentSize.size.width = ((i+1) * buttonWidth) + (i * buttonSpacing);
self.contentView.frame = contentSize;
thisX += buttonWidth + buttonSpacing;
}
【问题讨论】:
-
我认为您可以在循环之后设置一次
contentSize.size.width,而不是在每次迭代时设置它。 -
同意,除了 int 的值是循环的本地值。无论哪种方式,简单的解决方案。
标签: ios objective-c uiview uilabel