Anonymous White Anonymous White - 1 year ago 79
Objective-C Question

How do I sizeToFit a UILabel by changing only the height and not the width?

[self.Review sizeToFit];

Result before sizeToFit:

NSStringFromCGRect(self.Review.frame): {{90, 20}, {198, 63}}

Result After sizeToFit:

NSStringFromCGRect(self.Review.frame): {{90, 20}, {181, 45}}

I want the width to remain the same. I just want to change the height. THe automask is

(lldb) po self.Review
(UILabel *) $1 = 0x08bb0fe0 <UILabel: 0x8bb0fe0; frame = (90 20; 181 45); text = 'I'm at Mal Taman Anggrek ...'; clipsToBounds = YES; opaque = NO; autoresize = LM+RM+H; userInteractionEnabled = NO; layer = <CALayer: 0x8bb68b0>>

I know that there is a way to do so with:
how to adjust and make the width of UILabel fit to the text size

The answers are either strange (we need to resupply the font information). Or unclear.

You will also need to define a maximum width, and tell your program
what to do if sizeToFit gives you a width greater than that maximum.

I will use the strange solution of using
. It's strange because UILabel already knows the font in the label.

Actually how does sizeToFit behave anyway? How does it decide whether we need thinner or taller UILabel?

Answer Source

This is how it is done. Because the label already contains the font information, including it in this method call is trivial.

CGSize size = [label.text sizeWithFont:label.font
                     constrainedToSize:CGSizeMake(maxWidth, MAXFLOAT)
CGRect labelFrame = label.frame;
labelFrame.size.height = size.height;
label.frame = labelFrame;

Swift version using the more up-to-date boundingRectWithSize:

let maxHeight : CGFloat = 10000
let rect = label.attributedText?.boundingRectWithSize(CGSizeMake(maxWidth, maxHeight), 
       options: .UsesLineFragmentOrigin, context: nil)
var frame = label.frame
frame.size.height = rect.size.height
label.frame = frame
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download