Search code examples
swiftuicollectionviewuilabelsizetofit

Is there any accurate way of calculating size of UILabel without using sizeToFit?


I know this question is a long shot, but I am just wondering if someone found a better solution. Using boundingRect is not accurate as it does not work with word wrapping. The reason I do not wish to use sizeToFit is that it incurs quite a hefty performance penalty when there are a lot of labels to calculate, thus causing jerkiness during scrolling (I am using UICollectionView).


Solution

  • There is the internal method that makes sizeToFit possible - sizeThatFits(_ size: CGSize) -> CGSize. You can use it to compute the size without actually relayouting the view.

    Except that there's nothing more. There's a lot of methods, as you mentioned that compute bounding boxes of strings with different fonts/attributes/whatever, but they are always a little off, as the UI controls have inner layout or margins that are not publicly accessible. Even if you get it to work now it changes heavily from iOS to iOS.

    As a solution I propose caching the sizes. Invalidate on model changes, rotations or collection view width changes.