iPhone – Wrap Text in UILabel

In UILabel, there is an adjustsFontSizeToFitWidth property which will automatically adjust the text font size to fit the UILabel width.

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 20.0)];
aLabel.adjustsFontSizetoWidth = YES; // This is a must
aLabel.minimumFontSize = 8.0f; 
aLabel.numberOfLines = 1; // This is a must too =.=

But this only work for numberOfLines = 1

Luckily, i found a workaround from a blog post. Here comes to the solution.

// Initialize the Label, Text and Font
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 64.0, 320.0, 60.0)];
UIFont *aFont = [UIFont fontWithName:@"Helvetica" size:28.0];
NSString *aText = @"And I will love you, baby - Always. And I'll be there forever and a day - Always. I'll be there till the stars don't shine. Till the heavens burst and the words don't rhyme. And I know when I die, you'll be on my mind. And I'll love you - Always.";

// Logic for adjusting the size
for (NSInteger i = 28; i > 8; i--) {
	aFont = [aFont fontWithSize:i];
	// Limit the width to UILabel width
	CGSize constraintSize = CGSizeMake(320.0f, MAXFLOAT);
	CGSize labelSize = [aText sizeWithFont:aFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
	// Break the loop when text height < UILabel height
	if (labelSize.height <= 60.0f) {

// Set the font and text for UILabel
aLabel.font = aFont;
aLabel.text = aText;
aLabel.numberOfLines = 4;

// Add the Label to the view and release it
[self.view addSubview:aLabel];
[aLabel release];


Done =)



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.