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
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.
also my solution is the boolean label.adjustsFontSizeToFitWidth = YES; BUT. You must in the interface Builder the Word Wrapping switch to "CLIP". Then autoshrink the Labels. This is very important.
In iOS 9 I just had to:
Someone recommended setting number of lines to 0, but for me this just made the label go to multiple lines...
minimumFontSize
is deprecated in iOS 6.
So use minimumScaleFactor
instead of minmimumFontSize
.
lbl.adjustsFontSizeToFitWidth = YES
lbl.minimumScaleFactor = 0.5
Swift 5
lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5
Two years on, and this issue is still around...
In iOS 8 / XCode 6.1, I was sometimes finding that my UILabel
(created in a UITableViewCell
, with AutoLayout turned on, and flexible constraints so it had plenty of space) wouldn't resize itself to fit the text string.
The solution, as in previous years, was to set the text, and then call sizeToFit
.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
. . .
cell.lblCreatedAt.text = [note getCreatedDateAsString];
[cell.lblCreatedAt sizeToFit];
}
(Sigh.)