首页 > 代码库 > TabelViewCell自适应高度

TabelViewCell自适应高度

1.首先,设置 cell 中显示文本的容器(这里假设是 Label)的一些属性,如下:


[_LabelsetNumberOfLines:0];//这个是设置 label 内文本的行数,0 代表自适应

[_LabelsetLineBreakMode:NSLineBreakByWordWrapping];//断行模式

[_LabelsetFont:[UIFontsystemFontOfSize:16.0]];//字体大小


2.在 Cell 的 - (void)layoutSubviews 方法中,重新设置 cell 中 Label 的高度(根据自适应换行后计算高度)


NSString * text = [_array objectAtIndex:indexPath.row];

cell.Label.text = text;//从数据源中获得相对应的数据

NSDictionary * dic = [NSDictionarydictionaryWithObject:[UIFontsystemFontOfSize:16.0]forKey:NSFontAttributeName];//这里的字体大小要跟你设置的 Label 字体大小一样

CGSize textSize = [textsizeWithAttributes:dic];//根据字典中的数据计算出 size

CGRect rect = _Label.frame;

rect.size.height = textSize.height;

_Label.frame = rect;

3.最后,修改 Cell 的行高,在设置 Cell 行高的协议方法中再计算一次


NSString * text = [_array objectAtIndex:indexPath.row];

cell.Label.text = text;//从数据源中获得相对应的数据

NSDictionary * dic = [NSDictionarydictionaryWithObject:[UIFontsystemFontOfSize:16.0]forKey:NSFontAttributeName];//这里的字体大小要跟你设置的 Label 字体大小一样

CGSize textSize = [textsizeWithAttributes:dic];//根据字典中的数据计算出 size

return textSize.height;