首页 > 代码库 > cell动态高度
cell动态高度
1. 在自定义cell的layoutsubview方法里:
// 动态设置cell的高度
// 1. 核心代码
CGSize constraint = CGSizeMake(kWidth, 20000.0f);
NSAttributedString *attributedText = [[NSAttributedStringalloc]initWithString:_label.textattributes:@{
NSFontAttributeName:[UIFontsystemFontOfSize:kFont]
}];
CGRect rect = [attributedText boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
// 2. 设置frame
_label.frame = CGRectMake(10, 10, kWidth, size.height);
2.在控制器的
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Model *model = _models[indexPath.row];
NSString *text = model.text;
// 动态设置cell的高度
// 1. 核心代码
CGSize constraint = CGSizeMake(kWidth, 20000.0f);
NSAttributedString *attributedText = [[NSAttributedStringalloc]initWithString:text attributes:@{
NSFontAttributeName:[UIFontsystemFontOfSize:kFont]
}];
CGRect rect = [attributedText boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
// 2. 设置高度
return size.height + 20;
}
cell动态高度