#pragma mark 根据模型计算出整个cell的高度
+(CGFloat)calcHeightForCellWithStudent:(Student *)student;
======================
-(void)setStudent:(Student *)student
{
_nameLabel.text = student.name;
_introduceLabel.text = student.introduce;
//得到文字后,计算高度
CGFloat height = [self calcHeightWithStudent:student];
//将得到的高度重新赋值给_introduceLabel
// _introduceLabel.frame = CGRectMake(_introduceLabel.frame.origin.x, _introduceLabel.frame.origin.y, _introduceLabel.frame.size.width, height);
//优化上面的代码
CGRect frame = _introduceLabel.frame;
frame.size.height = height;
_introduceLabel.frame = frame;
}
#pragma mark 根据模型计算高度
//传入student为了 提高复用性 万一 还有其他的内容来决定这个高度呢。
-(CGFloat)calcHeightWithStudent:(Student *)student
{
//1.设置计算文字所在的最大范围
CGSize size = CGSizeMake(_introduceLabel.frame.size.width, 1000);
//2.创建字典,包含字体大小
NSDictionary *dic = @{
NSFontAttributeName:_introduceLabel.font
};
//3.使用方法,去返回文字的frame
CGRect rect = [student.introduce boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
//4.返回frame中的高度值
return rect.size.height;
}
#pragma mark 根据模型计算出整个cell的高度
+(CGFloat)calcHeightForCellWithStudent:(Student *)student{
//创建一个对象,执行计算label高度的方法,获取高度。
CGFloat labelHeight = [[InformationCell new] calcHeightWithStudent:student];
//返回可变高度 + 固定高度即可。
return 70 + labelHeight;
}
=====================================
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Student *stu = _bigArray[indexPath.row];
if ([stu.gender isEqualToString:@"male"]) {
return [StudentCell calcHeightForCellWithStudent:stu];
}else
{
//使用InfoCell提供的方法,根据stu模型计算整个cell需要的高度。
//之前那为什么使用类方法,就是为了外界使用“我”的时候,比较方便,如果用了实例方法的话,这里还要创建对象,会比较麻烦。
return [InformationCell calcHeightForCellWithStudent:stu];
}
}