OK, 在了解了如何計算tableView的高度之后,是不是應該了解一下更加簡單的辦法計算高度以及高度計算方面的優化工作呢
通過xib約束進行cell便捷高度計算
- 1,創建xib后進行正確的約束:
正確的意思是:內部的空間必須要把view的本身高度撐起來,如下
Snip20170113_3.png
- 2,cell內部接受到數據后只需要進行簡單的賦值即可
- (void)setStatus:(IMStatus *)status{
_status = status;
self.iconView.image = [UIImage imageNamed:status.icon];
self.nameLabel.text = status.name;
self.vipView.image = [UIImage imageNamed:@"vip"];
self.textView.text = status.text;
}
- 3, 在控制器中也比較簡單
- 從xib中加載,并設置estimatedRowHeight,其值可以是非零的任意值
[self.tableView registerNib:[UINib nibWithNibName:@"IMTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
// self.tableView.rowHeight = UITableViewAutomaticDimension;//ios8以后這個是默認值可以不設置
self.tableView.estimatedRowHeight = 5//只需要非零即可
- cellForCell方法內部也就是接受下數據即可
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
IMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
cell.status = _statuses[indexPath.row];
return cell;
}
優化
優化方法是用的百度iOS孫源的框架,具體的內容我覺得他講的非常好,直接把地址拿過來了
UITableView+FDTemplateLayoutCell
優化UITableViewCell高度計算的那些事
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
return [tableView fd_heightForCellWithIdentifier:@"cell" cacheByIndexPath:indexPath configuration:^(IMTableViewCell *cell) {
// 配置 cell 的數據源,和 "cellForRow" 干的事一致,比如:
cell.status = _statuses[indexPath.row];
}];
}