UILabel is not auto-shrinking text to fit label size

后端 未结 17 611
感动是毒
感动是毒 2020-12-04 06:53

I have this strange issue, and im dealing with it for more than 8 hours now.. Depending on situation i have to calculate UILabels size dynamically,
e.g

17条回答
  •  春和景丽
    2020-12-04 07:47

    Coming late to the party, but since I had the additional requirement of having one word per line, this one addition did the trick for me:

    label.numberOfLines = [labelString componentsSeparatedByString:@" "].count;

    Apple Docs say:

    Normally, the label text is drawn with the font you specify in the font property. If this property is set to YES, however, and the text in the text property exceeds the label’s bounding rectangle, the receiver starts reducing the font size until the string fits or the minimum font size is reached. In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1.

    But this is a lie. A lie I tell you! It's true for all iOS versions. Specifically, this is true when using a UILabel within a UICollectionViewCell for which the size is determined by constraints adjusted dynamically at runtime via custom layout (ex. self.menuCollectionViewLayout.itemSize = size).

    So when used in conjunction with adjustsFontSizeToFitWidth and minimumScaleFactor, as mentioned in previous answers, programmatically setting numberOfLines based on word count solved the autoshrink problem. Doing something similar based on word count or even character count might produce a "close enough" solution.

提交回复
热议问题