Calculating multiline text height for UILabel/UITableViewCell: different results when calculating vs actual drawing

前端 未结 3 885
情深已故
情深已故 2021-01-30 05:09

This general topic has been asked here multiple times: how to render UITableViewCells with varying amount of text and thus varying height. The canonical answer is: you calculate

相关标签:
3条回答
  • 2021-01-30 05:44
     titleSize = [title sizeWithFont:[UIFont systemFontOfSize:(CGFloat)17.0]
                                    constrainedToSize:CGSizeMake(280, 2000)
                                        lineBreakMode:NSLineBreakByWordWrapping];
    
    0 讨论(0)
  • 2021-01-30 05:53

    Of course, the solution is obvious 30 seconds after posting. Maybe useful to others too...

    The size by sizeWithFont: was correct. The sizes I calculated in the above way were incorrect, because [label sizeToFit] reduces the width of the label's frame. At subsequent calls to the same code, it started off with the frame that may already have been reduced.

    The fix was to simply reset the frame width to a known good width before sizing to fit:

    CGRect labelFrame = label.frame;
    labelFrame.size.width = 310;
    label.frame = labelFrame;
    [label sizeToFit];
    
    0 讨论(0)
  • 2021-01-30 05:56

    For multiline labels you need set

    cell.textLabel.numberOfLines = 0;
    

    and then

    [cell.textLabel sizeToFit];
    

    But for pretty view you need add some padding pixels. And your app will be awesome!

    0 讨论(0)
提交回复
热议问题