Calculate UITableViewCell height to fit string

前端 未结 2 1633
悲&欢浪女
悲&欢浪女 2020-12-07 05:42

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 a

2条回答
  •  太阳男子
    2020-12-07 06:29

    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 = ;
    
        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.

提交回复
热议问题