我目前正在将iOS应用程序移植到自动布局,我发现了一个无法解决的问题。问题是UITableView
。
表非常简单:
第1点和第2点很简单但我不知道如何创建一个约束来强制不同单元格中的视图具有相同的大小。
是否有自动布局解决方案或我是否必须手动设置框架?
答案 0 :(得分:2)
我会通过使用两个标签创建自定义单元格类来完成此操作。为左边标签指定一个宽度约束(以及对单元格左边缘和centerY的约束),并为右边标签提供一个水平间距约束。将IBOutlets设置为两个标签,并将一个设置为左标签的宽度约束(在我的示例中,我称之为widthCon)。在我的例子中,我给两个标签一个背景颜色,所以我可以看到宽度。我在viewDidLoad中计算最长字符串的宽度,然后使用该数字调整cellForRowAtIndexPath中宽度约束的常量:
@interface TableController ()
@property (strong,nonatomic) NSArray *theData;
@property (nonatomic) CGFloat maxWidth;
@end
@implementation TableController
- (void)viewDidLoad {
[super viewDidLoad];
self.theData = @[@"One",@"Two",@"Three Hundred Forty",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine"];
self.maxWidth = 0;
for (NSString *s in self.theData) {
CGSize stringSize = [s sizeWithFont:[UIFont systemFontOfSize:17]];
if (stringSize.width > self.maxWidth) self.maxWidth = stringSize.width;
}
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.widthCon.constant = self.maxWidth;
cell.leftLabel.text = self.theData[indexPath.row];
return cell;
}