iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Thursday, August 5, 2010

UILabel dynamic sizing based on string

Here's how to create a UILabel that dynamically resizes to fit the NSString that is loaded into it:
UILabel *tmpTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
self.titleLabel = tmpTitleLabel;
[tmpTitleLabel release];
self.titleLabel.textColor = [UIColor blackColor];
self.titleLabel.font = [UIFont boldSystemFontOfSize:16];
self.titleLabel.numberOfLines = 0;
self.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
self.titleLabel.text = self.myTitleString;
//Calculate the expected size based on the font and linebreak mode of label
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize expectedLabelSize = [self.myTitleString sizeWithFont:self.titleLabel.font constrainedToSize:maximumLabelSize lineBreakMode:self.titleLabel.lineBreakMode];
//Adjust the label the the new height
CGRect newFrame = self.titleLabel.frame;
newFrame.size.height = expectedLabelSize.height;
self.titleLabel.frame = newFrame;
And here's the explanation of what's going on with this code:

Lines 1-3: Declare your UILabel using initWithFrame. At this point the size doesn't matter so use any frame size.

Lines 4-7: Sets the display properties for the UILabel.

Line 8: Set the string. In this case self.myTitleString is an NSString.

Line 11: Determine the maximum size for your label. In this case, I'm constraining to 300px wide, with an unlimited height.

Line 12: This is what creates the new size based on the string.

Lines 15-17: Sets the newly calculated frame for self.titleLabel.

Labels: , , ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home

« Older Entries  
Newer Entries »