簡體   English   中英

如何通過使用UILabel的內容計算自定義UITableViewCell的高度

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

如何使用表格視圖單元格中的UILabel內容計算自定義UITableViewCell的高度?

像這樣實現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