Search code examples
objective-cuitableviewcellrow-height

sizeWithFont: and sizeWithAttributes: don't work for a long single line


I'm trying to set a dynamic height for cells in my table, height should be based on a text length and a max width.

The problem appears when this text comes in a single line, without line separators. Doesn't matter how large the text is, if there are no line separators it detects that text fits in a single line so my cell height doesn't increase.

Am I doing something wrong? How can I achieve it? Thanks.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    CGFloat cellheight = 35.0f; // BASE

    NSString *text = @"...";

    if (text) {
    UIFont *font = (indexPath.row == 0) ? [UIFont systemFontOfSize:14] : [UIFont systemFontOfSize:12]; 
    CGSize constraintSize = CGSizeMake(self.tableView.frame.size.width, CGFLOAT_MAX);

    if (IS_EARLIER_THAN_IOS7) {
        CGSize size = [text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByCharWrapping];
        cellheight += size.height;
    } else {
        CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0f]}];

        CGSize adjustedSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
        cellheight += adjustedSize.height;
    }
    return (indexPath.row == 0) ? cellheight + 40.0f : cellheight;
}  

}


Solution

  • - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:") __TVOS_PROHIBITED; // NSTextAlignment is not needed to determine size
    

    You should use "boundingRectWithSize:options:attributes:context:" not "sizeWithAttributes:".

    This is a sample

    CGSize size = [text boundingRectWithSize:CGSizeMake(_myTableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size;