Dynamic label frame from unknown text length

suggest change

Resize a UILabel when the text length is not known ahead of time. Here the width is fixed at 280 points and the height limit passed to sizeThatFits is 9999. A newly created label has a zero frame, so set the width as well as the measured height. label in the Swift sample is that label, and it already has a font.

Objective-C

UILabel * label = [[UILabel alloc] init];

NSString *message = @"Some dynamic text for label";

//set the text and style if any.
label.text = message;

label.numberOfLines = 0;

CGSize maximumLabelSize = CGSizeMake(280, 9999); //280:max width of label and 9999-max height of label.

// use font information from the UILabel to calculate the size
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];

//Deprecated in iOS 7.0
//CGSize expectedLabelSize = [message sizeWithFont:label.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];

// create a frame that is filled with the UILabel frame data
CGRect newFrame = label.frame;

// The width stays 0 unless it is set. The height comes from sizeThatFits.
newFrame.size.width = 280;
newFrame.size.height = expectedLabelSize.height;

// put calculated frame into UILabel frame
label.frame = newFrame;

Swift

var message: String = "Some dynamic text for label"
//set the text and style if any.
label.text = message
label.numberOfLines = 0
var maximumLabelSize: CGSize = CGSize(width: 280, height: 9999)
var expectedLabelSize: CGSize = label.sizeThatFits(maximumLabelSize)
// create a frame that is filled with the UILabel frame data
var newFrame: CGRect = label.frame
// The width stays 0 unless it is set. The height comes from sizeThatFits.
newFrame.size.width = 280
newFrame.size.height = expectedLabelSize.height
// put calculated frame into UILabel frame
label.frame = newFrame

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents