自定义 cell 自适应高度

时间:2023-03-08 23:44:03
自定义 cell  自适应高度

#import "CommodityCell.h"

#import "UIImageView+WebCache.h"

@implementation CommodityCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

if (self) {

// Initialization code

[self addAllViews];

}

return self;

}

#pragma mark 加载全部控件

- (void)addAllViews

{

// 图片

self.photoImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(kMargin, kMargin, kWidth, kWidth)] autorelease];

_photoImageView.backgroundColor = [UIColor clearColor];

[self.contentView addSubview:_photoImageView];

// 标题

self.titleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_photoImageView.frame) + kMargin, kMargin, 225, kWidth / 2 - 10)] autorelease];

_titleLabel.backgroundColor = [UIColor clearColor];

_titleLabel.font = [UIFont boldSystemFontOfSize:17];

[self.contentView addSubview:_titleLabel];

_titleLabel.numberOfLines = 0;

// 详情

self.introduceLabel = [[[UILabel alloc] initWithFrame:CGRectMake(140, CGRectGetMaxY(_titleLabel.frame) + kMargin, 225, kWidth / 2)] autorelease];

_introduceLabel.backgroundColor = [UIColor clearColor];

_introduceLabel.numberOfLines = 0;

[self.contentView addSubview:_introduceLabel];

// 关闭交互

self.contentView.userInteractionEnabled = NO;

}

#pragma mark - 计算模型内某个字符串的高度

+ (CGFloat)calsLabelHeightWithCommodity:(Commodity *)commodity

{

// size: 表示允许文字所在的最大范围

// options: 一个参数,计算高度是使用  NSStringDrawingUsesLineFragmentOrigin

// attribute: 表示文字的某个属性(通常是文字大小)

// context: 上下文对象,通常写nil

CGRect rect = [commodity.Descripition boundingRectWithSize:CGSizeMake(225, 500) options:NSStringDrawingUsesLineFragmentOrigin

attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17]}

context:nil];

return rect.size.height;

}

#pragma mark 使用模型方法,返回模型内容在自己内部显示应该的高度

+ (CGFloat)cellHeightWithCommodity:(Commodity *)commodity

{

CGFloat a = 50 + 3 * kMargin + [self calsLabelHeightWithCommodity:commodity];

CGFloat b = kMargin + kWidth; // 图片的高度

if (a < b) {

return b;

} else {

return a;

}

}

#pragma mark 重写 commodity的setter方法

- (void)setCommodity:(Commodity *)commodity

{

NSLog(@"%@", commodity.Descripition);

if (_commodity != commodity) {

[_commodity release];

_commodity = [commodity retain];

}

//1.标题

self.titleLabel.text = _commodity.title;

//2.1 自适应高度

CGRect frame = _introduceLabel.frame;

frame.size.height = [CommodityCell calsLabelHeightWithCommodity:_commodity];//调整高度

_introduceLabel.frame = frame;

//2.2显示文字

self.introduceLabel.text = _commodity.Descripition;

//3. SDWebImage 异步加载图片

[self.photoImageView sd_setImageWithURL:[NSURL URLWithString:_commodity.s_image_url]];

}