最近再做个项目需要使用UITableView来显示评论列表,但是有的评论字数特别多,固定的Cell高度显示不完,只能动态地根据字数来设置Cell的高度了
只要实现UITableViewDelegate的
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath方法,动态返回cell的高度
核心代码如下:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat contentWidth = self.mainTableView.frame.size.width;//得到屏幕宽度
NSString *content = @“这里是评论的文字内容”;
CGRect rect = [content boundingRectWithSize:CGSizeMake( contentWidth, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];//根据content的文字,系统默认字体,字体大小为14来计算得到rect
return rect.size.height;//只要返回上一步得到的rect的高度即可
}