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
328 views
in Technique[技术] by (71.8m points)

cocoa touch - How do I get -[NSString sizeWithFont:forWidth:lineBreakMode:] to work?

I updated my question "Sizing a UILabel (in the iPhone SDK) to fit?" with a description of my problem with a suggested solution, but didn't get an answer. Perhaps I'll have better results by asking a new question...

I set a breakpoint after the following code:

NSString *theText = @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.";
CGSize theSize = [theText sizeWithFont:[UIFont systemFontOfSize:17.0f] forWidth:260.0 lineBreakMode:UILineBreakModeWordWrap];

theSize.height is 21 and theSize.width is 231. What am I doing wrong? That height can't be in pixels nor in number of lines.

Note that [UIFont systemFontOfSize:17.0f] is meant to specify the default font.

Update: I changed the code to:

CGSize constraintSize;
constraintSize.width = 260.0f;
constraintSize.height = MAXFLOAT;
NSString *theText = @"When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.";
CGSize theSize = [theText sizeWithFont:[UIFont systemFontOfSize:17.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

theSize.height is 273. That seems more like it.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

That height is in pixels. I expect it's truncating, i.e. giving you the metrics you'd see if you set this text on a UILabel with 1 line.

Try using sizeWithFont:constrainedToSize: and just give it MAXFLOAT for the height component of the size.


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

...