Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

objective c - 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 a UILabel to fit 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 sizeWithFont. 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?

question from:https://stackoverflow.com/questions/13067839/how-do-i-sizetofit-a-uilabel-by-changing-only-the-height-and-not-the-width

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
                         lineBreakMode:UILineBreakModeWordWrap]; 
CGRect labelFrame = label.frame;
labelFrame.size.height = size.height;
label.frame = labelFrame;

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

let maxHeight = CGFloat.infinity
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...