Fit text in UILabel Fit text in UILabel ios ios

Fit text in UILabel


I think you just need to add this:

label.adjustsFontSizeToFitWidth = YES;label.minimumFontSize = 0;

Then the text will automatically resize to fit the label.

Note however that this will only really work if the label.numberOfLines = 1, so that the text is on a single line.

If you need the text to wrap onto multiple lines but still shrink to fit, the solution is more complex. To do this, you need to calculate the rendered size of the text and then reduce it in a loop, as follows:

NSString *theText = @"A long string";CGRect labelRect = CGRectMake(10, 50, 300, 50);label.adjustsFontSizeToFitWidth = NO;label.numberOfLines = 0;CGFloat fontSize = 30;while (fontSize > 0.0){    CGSize size = [theText sizeWithFont:[UIFont fontWithName:@"Verdana" size:fontSize] constrainedToSize:CGSizeMake(labelRect.size.width, 10000) lineBreakMode:UILineBreakModeWordWrap];    if (size.height <= labelRect.size.height) break;    fontSize -= 1.0;}//set font sizelabel.font = [UIFont fontWithName:@"Verdana" size:fontSize];

This basically just reduces the font size until it fits the label.

UPDATE:

As of iOS7, multiline text will also shrink automatically when adjustsFontSizeToFitWidth = YES, so the second part of this answer is no longer needed (unless you still support iOS 6 and earlier).


Finally I got solution for text allignment issue in arabic language you just do like this:

    label.text = @"هذا هو نص طويل جدا";    label.textAlignment = NSTextAlignmentNatural;    CGSize size = [labels sizeThatFits:CGSizeMake(_lblAddress.width, CGFLOAT_MAX)];    label.height = size.height;


[UILabel sizeToFit];

It will work for your problem.