步骤:
1.创建一个继承自UITableViewCell的类。
2.将cell中要用到的视图都声明成属性
3.将这些视图都添加到cell的contentView上
4.将数据对象也声明成属性,并重写数据对象的setter方法,将该数据模型的属性赋值给cell中的视图上。
5.根据文本内容自定义cell的高度的主要代码:
.h文件中的代码:
@interface MyCell : UITableViewCell
//cell要用的视图
@property(nonatomic,strong) UILabel *nameLabel;
@property(nonatomic,strong) UILabel *introduceLabel;
//数据模型
@property(nonatomic,strong) Student *student;
//根据模型计算出整个cell的高度
+(CGFloat)calcHeightForCellWithStudent:(Student *)student;
@end
.m文件中的主要代码:
@implementation MyCell
//初始化方法
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self addAllViews];
}
return self;
}
-(void)addAllViews
{
//创建两个lable
self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, self.frame.size.width-20, 40)];
//设置文字居中
self.nameLabel.textAlignment = NSTextAlignmentCenter;
[self.contentView addSubview:_nameLabel];
self.introduceLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 60, self.frame.size.width-20, 80)];
//设置自动换行
self.introduceLabel.numberOfLines = 0;
[self.contentView addSubview:_introduceLabel];
self.introduceLabel.backgroundColor = [UIColor cyanColor];
}
//重写setter方法(将数据模型的属性赋值给cell的视图)
-(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);
//方法二:将得到的高度重新赋值给_introduceLabel的高度
CGRect frame = _introduceLabel.frame;
frame.size.height = height;
_introduceLabel.frame = frame;
}
#pragma mark----------根据模型计算高度
//注意:传一个模型过来是方便以后更改
-(CGFloat)calcHeightWithStudent:(Student *)student
{
//1.计算文字所在的最大范围
CGSize size = CGSizeMake(_introduceLabel.frame.size.width, 1000);
//2.创建一个字典,包含字体大小
NSDictionary *dict = @{NSFontAttributeName:_introduceLabel.font};
//使用方法,去计算文字的frame
CGRect frame = [student.introduce boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
//返回文字的高度
return frame.size.height;
}
#pragma mark----------根据模型计算出整个cell的高度
+(CGFloat)calcHeightForCellWithStudent:(Student *)student
{
//创建一个对象,执行计算label的高度
CGFloat labelHeight = [[[MyCell alloc]init]calcHeightWithStudent:student];
//将固定高度和得到的label高度相加
return 70+labelHeight;
}
//注意:设置整个cell的高度的方法比设置整个cell的内容先执行,小心设置cell的高度时字典内容为空,程序会崩溃,是因为执行高度设置时视图内没有内容,这个问题在xib中容易出现。