简体   繁体   English

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

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

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

Implement your heightForRowAtIndexPath like this: 像这样实现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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM