If the sizeWithFont:constrainedToSize:lineBreakMode:
method is deprecated in iOS7, how can I automatically resize a UILabel
to dynamically adjust its height and width to fit the text?
I ended up using this. Works for me. This does not work with IBOutlets object but useful when computing dynamically the height of the text on uitableview's heightForRowAtIndexPath: method.
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"FontName" size:15], NSFontAttributeName,
nil];
CGRect frame = [label.text boundingRectWithSize:CGSizeMake(263, 2000.0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
This should work in iOS6 and iOS7, but will break your label constraints (you need to set them all back programatically if needed):
-(void)resizeHeightForLabel: (UILabel*)label {
label.numberOfLines = 0;
UIView *superview = label.superview;
[label removeFromSuperview];
[label removeConstraints:label.constraints];
CGRect labelFrame = label.frame;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
CGRect expectedFrame = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, 9999)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
label.font, NSFontAttributeName,
nil]
context:nil];
labelFrame.size = expectedFrame.size;
labelFrame.size.height = ceil(labelFrame.size.height); //iOS7 is not rounding up to the nearest whole number
} else {
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
labelFrame.size = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, 9999)
lineBreakMode:label.lineBreakMode];
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
}
label.frame = labelFrame;
[superview addSubview:label];
}
Add this method to your viewController and use it like this:
[self resizeHeightForLabel:myLabel];
//set new constraints here if needed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With