cell自适应高度

cell自适应高度

方式一:在自定义cell的自适应高度

1、在自定义cell的.h文件中声明两个类方法

//求一段文本的显示高度

+ (CGFloat)heightForString:(NSString *)string;

//求cell的高度

+ (CGFloat)cellHeightForStudent:(Student *)student;

2、在自定义cell的.m文件中写方法的实现

//求一段文本的显示高度

+ (CGFloat)heightForString:(NSString *)string {

    

    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];

    

    CGRect rect = [string boundingRectWithSize:CGSizeMake(3 *kImageWidth, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

    return rect.size.height;

}

//返回cell的高度

+ (CGFloat)cellHeightForStudent:(Student *)student {

    CGFloat totalHeight = 65 + [GirlTableViewCell heightForString:student.introduce];

    return  totalHeight > 120 ? totalHeight : 120;

}

3、遵循协议- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath设定cell的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        return [MyTableViewCell cellHeightForStudent:student];

}

4、在自定义cell的LayoutSubViews方法中设定子视图的高度

_introduceLabel.frame = CGRectMake(10, 65, 3 * imageWidth, [MyTableViewCell heightForString:self.student.introduce]);

方式二:系统cell的自适应高度

1、文本自适应高度,根据文本内容设定高度

NSString *str = @“dibibfnbdfbiehiehiorjogjteobjoebmtlrmnklgrou9q7924529854038510280ifopkwolvbnnbeijoejorjgesgfndbkndfbivjfi” ; 

// 获取字体样式属性

      NSDictionary *att = @{NSFontAttributeName:[UIFont

  systemFontOfSize:17.0]};

// 根据字体样式属性获取高度

      CGRect rect = [str boundingRectWithSize:CGSizeMake(200, 10000) options:NSStringDrawingUsesLineFragmentOrigin  attributes:att context:nil];

      [self.showLabel setFrame:CGRectMake(0, 0, 200, rect.size.height)];

2、图片自适应高度,根据图片宽度进行等比缩放

UIImage *aImage = [UIImage imageNamed:@"1.png"]; 

// 获取图片真实高度
CGFloat height = aImage.size.height;
CGFloat width = aImage.size.width; 

// 缩放后宽度固定为150
CGFloat scale = width / 150;
CGFloat realHeight = height / scale;

 [self.myImageView setFrame:CGRectMake(0, 0, 200,realHeight)];

原文地址:https://www.cnblogs.com/d-mm/p/5210181.html