Cell自适应高度

来源:互联网 发布:欧树蜂蜜洁面凝胶 知乎 编辑:程序博客网 时间:2024/06/01 07:16

让Cell自动适应高度

自定义cell

#import "MyCell.h"//contentView是每个cell的view//下面的define是定义成每个cell的高度和宽度#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];//    指定lable的字体大小,默认是17号    self.Mylable.font = [UIFont systemFontOfSize:14];//    0是最大行数    self.Mylable.numberOfLines = 0;    [self.Mylable sizeToFit];    [self.contentView addSubview:self.Mylable];    [_Mylable release];}-(void)layoutSubviews{    [super layoutSubviews];//    让imageview的尺寸和cell的图片大小相同//    因为这个方法是最后一个被执行的,所以执行到这个方法的时候,已经对cell的各个属性进行完赋值操作,所以可以通过imageview.image找到图片的尺寸    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];    //    根据文本的大小,计算出文本的尺寸    //    还需要指定一个尺寸(375,0)    //    第三个参数:计算高度需要依据字体的哪个特征来确定    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找到image里面的图片尺寸    CGSize picSize = image.size;//    计算宽高    CGFloat rowHeight = picSize.height * self.view.frame.size.width / picSize.width;//    计算lable的高度//    根据对应的文字求出cell上lable显示的高度    NSDictionary *fontDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil];//    根据文本的大小,计算出文本的尺寸//    还需要指定一个尺寸(375,0)//    第三个参数:计算高度需要依据字体的哪个特征来确定    CGRect rect = [self.ziArr[indexPath.row]boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];//    把结果作为返回值返回    return rowHeight + rect.size.height;  }
0 0