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

前端 未结 3 884
情深已故
情深已故 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: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];
    

提交回复
热议问题