首页 > 代码库 > IOS 控件 - UITableView 中的cell 自适应高度

IOS 控件 - UITableView 中的cell 自适应高度

当 UITableView 中有一个 label 的内容比较长的时候,就需要 cell 自适应高度来多行展示label;

首先设置 label 的 line 为0;

代码如下:

// 为每一个 cell 预设置一个高度,可以提高效率- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {    return 44;}// 这里每一个 cell 的实际高度(即自适应高度)- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {    // 这里可以通过 if 判断语句来为你需要的那一行单独设置自适应高度    if (indexPath.row == [rowsArr count] - 1) {                // 通过数据来获取 label 所需要的高度        NSString *rowName = [rowsArr objectAtIndex:indexPath.row];        NSString *key = [rowsAndKeyDic objectForKey:rowName];        CGFloat descriptionH = [self textHeight:[taskDetailDic objectForKey:key]];                return descriptionH + 20;// 这个70 完全是根据你的情况调整的    }    return 44;}// 获取 label 实际所需要的高度- (CGFloat)textHeight:(NSString *)labelText {    UIFont *tfont = [UIFont systemFontOfSize:16.0];    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];    //  ios7 的API,判断 labelText 这个字符串需要的高度;    这里的宽度(self.view.frame.size.width - 140he)按照需要自己换就 OK    CGSize sizeText = [labelText boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 140, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;    return sizeText.height;}

 

IOS 控件 - UITableView 中的cell 自适应高度