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:
Read more »
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:
Read more »
Labels: dynamic size, expand, shrink, UILabel