第一種:根據文字內容設置估算高度自動計算
1.自定義cell
2.在cell里添加Label,設置Label上邊距和下邊距,設置自動換行,寬度用代碼設置
contentLabelWCons.constant = UIScreen.mainScreen().bounds.width - 2 * edgeMargin
然后設置
//高度自動計算
tableView.rowHeight = UITableViewAutomaticDimension
//估算高度
tableView.estimatedRowHeight = 200
第二種:根據文字所在范圍,計算
1.自定義cell
2.在cell里添加Label,設置Label上邊距和下邊距和#寬度約束#,設置自動換行
//確定范圍
CGSize textSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 4 * MAXMargin, MAXFLOAT);
//這里的字體設置要和Xib里邊Label設置的字體一致
CGFloat textH = [self.text boundingRectWithSize:textSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]} context:nil].size.height;
3.再實現一個代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
MAXContent *c = self.contents[indexPath.row];
return c.cellH;
}