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

时间:2014-04-21 04:44:26

标签: ios uitableview uilabel

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

1 个答案:

答案 0 :(得分:3)

像这样实施heightForRowAtIndexPath

- (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;
}