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

ios - Get the NSString height

I have an NSString, and I want to know its height to create an appropriate UILabel.

Doing this

NSString *string = @"this is an example"; 
CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:10.0f] 
                          forWidth:353.0 
                     lineBreakMode:UILineBreakModeWordWrap];
float height = size.height;

height is now 13.0. If I use this string

NSString *string = @"this is an example this is an example this is an example 
                     this is an example this is an example this is an example 
                     this is an example this is an example this is an example 
                     this is an example this is an example this is an example 
                     this is an example this is an example this is an example 
                     this is an example "; 

height is always 13.0 (and with 353 as width, that's impossible)... what am I doing wrong?

ADD:

size.width;

works fine... so it's like if the lineBreakMode is not correct... but it is, isn't it?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The reason what you're doing doesn't work as you would expect is because

– sizeWithFont:forWidth:lineBreakMode: 

is for "Computing Metrics for a Single Line of Text" whereas

-sizeWithFont:constrainedToSize:lineBreakMode:

is for "Computing Metrics for Multiple Lines of Text". From the documentation:

Computing Metrics for a Single Line of Text

– sizeWithFont:
– sizeWithFont:forWidth:lineBreakMode:
– sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

Computing Metrics for Multiple Lines of Text

– sizeWithFont:constrainedToSize:
– sizeWithFont:constrainedToSize:lineBreakMode:

Try using -sizeWithFont:constrainedToSize:lineBreakMode: instead, e.g. this is what I usually do:

CGSize maximumLabelSize = CGSizeMake(353,9999);

CGSize expectedLabelSize = [string sizeWithFont:label.font                        
                              constrainedToSize:maximumLabelSize 
                                  lineBreakMode:label.lineBreakMode]; 

CGRect newFrame = label.frame;
newFrame.size.height = expectedLabelSize.height;
label.frame = newFrame;

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

...