Auto Layout Cell Height

参考文章 iOS开发 - 处理不等高TableViewCell的小花招,实践出真知,也是费了一番力气才把文章 Cell 使用 Auto Layout自动算高。眼高手低总是有的,所以以后不仅要学习开发的思路方法论,重要是在实践一遍。

Auto Layout设置好高度约束。不要实现- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath

1
2
3
4
5
6
(void)viewDidLoad {
[super viewDidLoad];

self.tableView.estimatedRowHeight = 100; // 随便设个不那么离谱的值
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
- (TableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"
forIndexPath:indexPath];
cell.avatar.image = [UIImage imageNamed:@"avatar"];
cell.name.text = [NSString stringWithFormat:@"%ld", indexPath.row % 2];
cell.time.text = [NSString stringWithFormat:@"%@", [NSDate date]];
cell.source.text = @"Weibo.com";

NSMutableString *str = [NSMutableString new];
for (long i = 1; i < indexPath.row; i++) {
[str appendString:@"The 1989 World Tour (Live)"];
}
[str appendString:@"END!!!"];
cell.text.text = str;

//移除多余边框,如果是图片是 Aspect Fill 或者 Aspect Fit
cell.pic.layer.borderColor = [UIColor clearColor].CGColor;
cell.pic.layer.borderWidth = 0.1;
cell.pic.layer.masksToBounds = YES;

if (indexPath.row % 2 == 1) {
cell.pic.image = [UIImage imageNamed:@"pic"];
} else {
cell.pic.image = nil;
}

return cell;
}

源码:https://github.com/gewill/test-projects/tree/master/test%20auto%20height%20cell