UILabelでadjustsFontSizeToFitWidthが効かなくてハマった
UILabelのsubClassを作っていて、initializeをoverrideして案件で最適なLabelクラスを作っていた。
adjustsFontSizeToFitWidth = YESにセットしているのに、なぜかscaleしてくれない!
という問題が発生し、ハマってた。
UILabel.hの当該コメントを見て即解決した
以下コピペ
// these next 3 property allow the label to be autosized to fit a certain width by scaling the font size(s) by a scaling factor >= the minimum scaling factor // and to specify how the text baseline moves when it needs to shrink the font. this only affects single line text (lineCount == 1) @property(nonatomic) BOOL adjustsFontSizeToFitWidth; // default is NO @property(nonatomic) BOOL adjustsLetterSpacingToFitWidth NS_AVAILABLE_IOS(6_0); // default is NO, adjust letter spacing to make text fit. Note: setting this property to YES will cause the value of -[NSParagraphStyle tighteningFactorForTruncation] to be disgregarded. @property(nonatomic) CGFloat minimumFontSize NS_DEPRECATED_IOS(2_0, 6_0); // NOTE: deprecated - use minimumScaleFactor. default is 0.0
つまり、lineCountが1じゃないと効果がない。
今回問題になった原因は、initializeで
self.numberOfLines = 0; self.adjustsFontSizeToFitWidth = YES; self.minimumFontSize = 4.0f;
って感じでnumberOfLinesに1以外をセットしていたから。
もし改行させたいことが多いならデフォルトで0でもいいかもしれないけど、
xibで指定したのが効かない!って問題になりそうだから、コードでは指定しない方がいいのかな。