让Cell自动适应高度
自定义cell
#import "MyCell.h"
#define WIDTH self.contentView.frame.size.width
#define HEIGHT self.contentView.frame.size.height
@implementation MyCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self createView];
}
return self;
}
-(void)createView{
self.MyImageView = [[UIImageView alloc]init];
[self.contentView addSubview:self.MyImageView];
[self.MyImageView release];
self.Mylable = [[UILabel alloc]init];
self.Mylable.font = [UIFont systemFontOfSize:14];
self.Mylable.numberOfLines = 0;
[self.Mylable sizeToFit];
[self.contentView addSubview:self.Mylable];
[_Mylable release];
}
-(void)layoutSubviews{
[super layoutSubviews];
CGSize picSize = self.MyImageView.image.size;
CGFloat height = picSize.height * self.contentView.frame.size.width / picSize.width;
self.MyImageView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, height);
NSDictionary *fontDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil];
CGRect rect = [self.Mylable.text boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];
self.Mylable.frame = CGRectMake(0, height, self.contentView.frame.size.width, rect.size.height);
}
-(void)dealloc{
[_MyImageView release];
[super dealloc];
}
主视图中需要实现的让cell自适应的方法
#pragma mark 这个方法是tableview的delegate所提供的协议方法,主要是用来设置每一行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
UIImage *image = [UIImage imageNamed:self.picArr[indexPath.row]];
CGSize picSize = image.size;
CGFloat rowHeight = picSize.height * self.view.frame.size.width / picSize.width;
NSDictionary *fontDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil];
CGRect rect = [self.ziArr[indexPath.row]boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];
return rowHeight + rect.size.height;
}