Get the NSString height

末鹿安然 提交于 2019-11-27 03:22:25

问题


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?


回答1:


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;



回答2:


According to the Documentation

This method returns the width and height of the string constrained to the specified width. Although it computes where line breaks would occur, this method does not actually wrap the text to additional lines. If the size of the string exceeds the given width, this method truncates the text (for layout purposes only) using the specified line break mode until it does conform to the maximum width; it then returns the size of the resulting truncated string.

You should to use -[NSString sizeWithFont:constrainedToSize:lineBreakMode:] which has similar behavior but you can uuse CGFLOAT_MAX as the height in the size passed in.



来源:https://stackoverflow.com/questions/6962641/get-the-nsstring-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!