jdev
jdev

Reputation: 589

UILabel adjustFont with multiline

I have a UILabel which usually has to display one or two words.

Many times one of the words doesn't fit into one line, so I would like to reduce font size in order to fit each word at least in one line (not breaking by character).

Using the technique described in http://beckyhansmeyer.com/2015/04/09/autoshrinking-text-in-a-multiline-uilabel/

self.numberOfLines = 2;
self.lineBreakMode = NSLineBreakByTruncatingTail;
self.adjustsFontSizeToFitWidth = YES;
self.minimumScaleFactor = 0.65;

I've found that it plays well when the second word doesn't fit in just one line.

enter image description here

But it doesn't when there is just one word, or the first word is the one that doesn't fit. enter image description hereenter image description here

I managed to solve the case of just one word doing this:

-(void)setText:(NSString *)text
{
    self.numberOfLines =  [text componentsSeparatedByString:@" "].count > 1 ? 2 : 1;
    [super setText:text];
}

But how could I solve those cases where the first word doesn't fit?? Any ideas?

Upvotes: 0

Views: 263

Answers (1)

Pulkit Sharma
Pulkit Sharma

Reputation: 555

How about this ?

self.numberOfLines = [text componentsSeparatedByString:@" "].count;
[self setAdjustsFontSizeToFitWidth:YES];

But, this will rule out the case where your label text consists of two very small words, eg."how are". In such cases, the entire string will be visible in the first line itself. If it is your requirement to display each word in a separate line then i would recommend you adding a '\n' after every word. This means that you will have to edit the string before assigning it to the label. Thus, a universal solution could be like :

NSString *string = @"how are"; //Let this be the string
NSString *modifiedString = [string stringByReplacingOccurrencesOfString:@" " withString:@"\n"];
[self setText:modifiedString];
[self setTextAlignment:NSTextAlignmentCenter];
[self setAdjustsFontSizeToFitWidth:YES];
[self setNumberOfLines:0];
self.lineBreakMode = NSLineBreakByWordWrapping;

Upvotes: 1

Related Questions