简体   繁体   中英

Calculate UITableViewCell height to fit string

I have a NSMutableArray , which could contain several hundreds of different strings. Each string is user defined and could have any length, yet no more than an average paragraph.

I need to find out how many lines each string could take. So, I could calculate the required height for a every UITableviewCell .

Use the following code to calculate and to set the height for cell:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Define `veryverySmallTitleFont`
    // Define `descLabel`

    NSString *ourText = @"Your string data from array";
    UIFont *font = [UIFont fontWithName:@"Verdana" size:veryverySmallTitleFont];
    font = [font fontWithSize:veryverySmallTitleFont];

    CGSize constraintSize = CGSizeMake(descLabel.frame.size.width, 1000);
    CGSize labelSize = [ourText sizeWithFont:font
                           constrainedToSize:constraintSize
                               lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height;
}

I personally use a convenience method which I then send a message to in tableView:heightForRowAtIndexPath:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self cellHeightForRowAtIndexPath:indexPath];
}

- (CGFloat)cellHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellString = <YOUR MODEL OBJECT>;

    NSDictionary *attributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:16.0f] };
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
                                                   initWithString:cellString
                                                   attributes:attributes];

    CGFloat width = self.tableView.frame.size.width - 32.0f;
    CGRect frame = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                    options:NSStringDrawingUsesLineFragmentOrigin context:nil];

    // Add some extra padding to the height
    CGFloat height = frame.size.height + 16.0f;

    return ceil(height);
}

And of course, I set the numberOfLines property of my UILabel to 0 in UITableViewCell .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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