单元格上又一个label,显示的内容是从后台请求回来的,那么这个时候就需要单元格的高度根据返回的字符串的长度动态的改变。首先,我们需要计算出加载文本后,label的高度(此时的label一定要把numberOfLines设置为0)。我这里写了一个UILabel的类别;
.h里边的代码如下:
//初始化的size,size中高度或者宽度为0
-(CGRect)boundingRectWithInitSize:(CGSize)size;
.m里的代码如下:
//初始化的size,size中高度或者宽度为0
-(CGRect)boundingRectWithInitSize:(CGSize)size{
self.lineBreakMode=NSLineBreakByWordWrapping;
CGRect rect=[self.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.font,NSFontAttributeName, nil] context:nil];
return rect;
}
使用时代码如下:
thirdLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, [Utile returnViewFrame:lab direction:@”Y”]+10, ScreenWidth - 20, 0)];
thirdLabel.font = [UIFont systemFontOfSize:15];
thirdLabel.text = thirdStr;
thirdLabel.numberOfLines = 0;
CGRect thirdRect = [thirdLabel boundingRectWithInitSize:thirdLabel.frame.size];
thirdLabel.frame = CGRectMake(15, [Utile returnViewFrame:lab direction:@”Y”]+10, ScreenWidth - 20, thirdRect.size.height);
有了label的frame要改变cell的高度,只需如下代码格式:
- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath{
return lab.frame.size.height+thirdLabel.frame.size.height+fouthLabel.frame.size.height +140;
}