尝试做一些相当简单的事情。我正在创建一排放置在水平滚动UIScrollView
中的矩形。矩形布局完美。但是,每个矩形都放置了UILabel
。仅显示第一个标签。没有其他人。这里的红色矩形是基本的CGRect
。黄色是我调试标签是否正确绘制。您可以很容易地看到,只显示第一个标签:
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;
}
答案 0 :(得分:1)
您对UIView和UILabel使用相同的frame
。
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]; <-- this frame should have an origin.x of 0.0
label
的x来源应根据thisButton
的参考进行调整,因为您要将其添加为子视图。
答案 1 :(得分:0)
x origin
的{{1}}不会在循环中移动。这意味着您要在彼此之上创建所有UILabel
试试这个:
UILabel