我有一系列项目要显示在我的UITableViewCell. 这些项目中的每一个都将使用 动态显示UILabel。我使用自动布局来设置视图布局。
这是我的布局方式tableViewCell:
+------------------------------------------------+
| [cellView] |
| +---------------------------------------------+|
| |[otherView] <- fixed height ||
| | +------------------------------------------+||
| | |[UILabel] |||
| | +------------------------------------------+||
| +---------------------------------------------+|
| +---------------------------------------------+|
| |[itemView] ||
| | +---------------------------+ +------------+||
| | |[itemLabel] |-|[priceLabel]|||
| | +---------------------------+ +------------+||
| | +---------------------------+ +------------+||
| | |[itemLabel] |-|[priceLabel]|||
| | +---------------------------+ +------------+||
| | ||
| | --Add the next UILabels dynamically-- ||
| +---------------------------------------------+|
+------------------------------------------------+
为了清楚起见
otherView:UILabel里面有2个。固定高度。itemView: 里面有未知数量的itemLabel&priceLabel。将根据items.- 除了
itemLabel&之外,每个视图约束都是使用故事板设置的priceLabel。
在我的内部cellForRowAtIndexPath,我使用itemLabel&设置priceLabel约束constraintsWithVisualFormat:
for (NSDictionary *item in items) {
UILabel *itemLabel = [[UILabel alloc] init];
itemLabel.translatesAutoresizingMaskIntoConstraints = NO;
itemLabel.font = [UIFont systemFontOfSize:14.0f];
itemLabel.backgroundColor = [UIColor yellowColor];
itemLabel.text = [item valueForKey:@"item_name"];
[cell.itemView addSubview:itemLabel];
UILabel *priceLabel = [[UILabel alloc] init];
priceLabel.translatesAutoresizingMaskIntoConstraints = NO;
priceLabel.font = [UIFont systemFontOfSize:14.0f];
priceLabel.textAlignment = NSTextAlignmentRight;
priceLabel.backgroundColor = [UIColor greenColor];
priceLabel.text = [NSString stringWithFormat:@"RM %@", [item valueForKey:@"price"]];
[cell.itemView addSubview:priceLabel];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(cell.itemView, itemLabel, priceLabel);
[cell.itemView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[itemLabel]-5-[priceLabel(70)]|"
options:0
metrics:nil
views:viewsDictionary]];
[cell.itemView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[itemLabel]|"
options:0
metrics:nil
views:viewsDictionary]];
[cell.itemView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[priceLabel]|"
options:0
metrics:nil
views:viewsDictionary]];
}
最终结果如下。唯一的问题是itemLabel和priceLabelcreated 彼此重叠,而不是从上到下很好地对齐。


如何正确设置约束,以便itemLabel&priceLabel从上到下很好地对齐,并且itemView将根据其中的项目数调整大小?