I’ve set up a label and in the label is some text. Now I want to set up the font that all the text fits in the label. I used for that minimum font size, because the label text changes every day. But suddendly it wont work. I’m doing something wrong?
Here my code:
CGRect infoLabelRect = CGRectMake(10, 250, 260, 350);
UILabel *infoLabel = [[UILabel alloc] initWithFrame:infoLabelRect];
infoLabel.text = @"bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla";
infoLabel.numberOfLines = 9;
infoLabel.font = [UIFont systemFontOfSize:17];
infoLabel.minimumFontSize = 12;
infoLabel.adjustsFontSizeToFitWidth = YES;
infoLabel.textColor = [UIColor whiteColor];
infoLabel.textAlignment = NSTextAlignmentCenter;
infoLabel.backgroundColor = [UIColor clearColor];
infoLabel.shadowColor = [UIColor blackColor];
infoLabel.shadowOffset = CGSizeMake(0, 1);
[infoLabel sizeToFit];
I tried what rmaddy sad but there’s no text displayed.
Here is my code which doesnt work.
Any suggestions?
UILabel *infoLabel = [[UILabel alloc] initWithFrame:infoLabelRect];
NSString *text = @"bla bla bla";
UIFont *font = nil;
CGFloat points = 17;
CGFloat maxHeight = infoLabel.frame.size.height;
CGFloat textHeight;
do {
font = [UIFont systemFontOfSize:points];
CGSize size = CGSizeMake(infoLabelRect.size.width, 100000);
CGSize textSize = [text sizeWithFont:font constrainedToSize:size lineBreakMode: NSLineBreakByWordWrapping];
textHeight = textSize.height;
points -= 1;
} while (textHeight > maxHeight);
infoLabel.font = font;
infoLabel.textColor = [UIColor whiteColor];
infoLabel.textAlignment = NSTextAlignmentCenter;
infoLabel.backgroundColor = [UIColor clearColor];
infoLabel.shadowColor = [UIColor blackColor];
infoLabel.shadowOffset = CGSizeMake(0, 1);
[infoLabel sizeToFit];
[contentView addSubview:infoLabel];
The use of
minimumFontSizeis only applicable to label’s of one line. Multi-line or wrapping labels don’t attempt to adjust the font size.From the docs for
minimumFontSize:One solution is to make use of the
NSString sizeWithFont:constrainedToSize:lineBreakMode:method to calculate the font size need to make the label’s text fit in the allotted space.Edit: Something like should work (this is not tested, could be typos):