平時(shí)的開發(fā)中我們打交道最多的的可能就是UITableVIew了,那今天我們就總結(jié)下其動(dòng)態(tài)顯示高度的多種解決方法
Method 1 - iOS 8為我們提供的方法
self.tableView.rowHeight = UITableViewAutomaticDimension;
或者我們可以實(shí)現(xiàn)返回高度的代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
Method 2 - systemLayoutSizeFittingSize
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return 1 + size.height;
如果說我們的UILable要多行顯示的話要設(shè)置numberOfLines等于0酗捌,
xib的話還要設(shè)置UIlable的preferredMaxLayoutWidth
Method 3 - sizeWithFont
- (CGSize)sizeWithFont:(UIFont *)font
constrainedToSize:(CGSize)size
lineBreakMode:(NSLineBreakMode)lineBreakMode
由于該方法在iOS7之后已經(jīng)棄用我們可以用其替代方法來計(jì)算字符串的高度
Method 4 - 第三方庫(kù)
大家應(yīng)該熟知早前在百度知道團(tuán)隊(duì)的哥們的一個(gè)庫(kù)UITableView-FDTemplateLayoutCell(runtime + method swizzing實(shí)現(xiàn))
詳情請(qǐng)參考Demo-https://github.com/LargeShrimp/UITableViewCellDynamicHeight