IOS 开发之 cell高度自适应

来源:互联网 发布:淘宝宝贝下载阿尔法 编辑:程序博客网 时间:2024/05/21 12:49

如果此文帮助了您,请点击喜欢或评论,如果您喜欢我的文章请关注我,您的支持永远都是我前行的动力.

viewDidLoad

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.array = [NSArray arrayWithObjects:@"测试数据1测试数据1测试数据1测试数据1测试数据1",@"测试数据2测试数据2测试数据2测试数据2测试数据2测试数据2测试数据2",@"测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3测试数据3",@"测试数据测试数据测试数测试数据测试数据",@"测试数据4测试数据4",nil];
[self.tableView registerClass:[TableViewCell class] forCellReuseIdentifier:identifier];
}

cellForRow

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
cell.titleLable.text = _array[indexPath.row];

1.计算文本高度
CGFloat height = [self textHeight:_array[indexPath.row]];
2.改变lable的高度

cell.titleLable.frame = CGRectMake(10, 10, 394, height);
return cell;
}

heightForRow

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
height会比cellForRow先执行,所以我们需要先计算好cell的高度.
1.先获取当前行所对应的字符串
NSString *string = _array[indexPath.row];
2.计算字符串的高度
CGFloat height = [self textHeight:string];
3.返回计算好的高度

return height + 20; // 加上空白区域的高度
}

textHeight:(NSString *)string

自定义高度

-(CGFloat)textHeight:(NSString *)string{
传字符串返回高度
计算字符串所占的矩形区域的大小
CGRect rect =[string boundingRectWithSize:CGSizeMake(394, 9999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
返回高度
return rect.size.height;
}

转载请注明出处.

0 0
原创粉丝点击