关于ios:如何使用UILabel的内容计算自定义UITableViewCell的高度

How to calculate height of custom UITableViewCell by using UILabel's content

如何在表视图单元格中使用UILabel \\的内容来计算自定义UITableViewCell的高度?


像这样实现heightForRowAtIndexPath

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *text = [dataArray objectAtIndex:indexPath.row]; //your data string

    CGSize constraint = CGSizeMake(yourLabel.frame.size.width, 2000.0f);
    CGSize size;

    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [text boundingRectWithSize:constraint
                                            options:NSStringDrawingUsesLineFragmentOrigin
                                         attributes:@{NSFontAttributeName:yourLabel.font}
                                            context:context].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}