sizewithfont always returns the same value no matter what string is used

大憨熊 提交于 2019-12-12 13:43:33

问题


I want to calculate the height of a tableviewcell according to its text. I'm using

CGSize userInputSize = [userLabel sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] forWidth:[tableView frame].size.width-10 lineBreakMode:NSLineBreakByWordWrapping]  

but somehow the return value is always 22 (size of the font). Strange thing is that when I'm using

CGSize userInputSize = [userLabel sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] constrainedToSize:[tableView frame].size lineBreakMode:NSLineBreakByWordWrapping];

all works fine. But I would prefer the first version, so I can easily adjust the width. Why isn't it working?

Edit: sorry for the bad name convention, but userLabel is a NSString not a label


回答1:


sizeWithFont is a NSString method (UIKit additions). use:

CGSize userInputSize = [userLabel.text sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f] constrainedToSize:[tableView frame].size lineBreakMode:NSLineBreakByWordWrapping];

or

CGSize userInputSize = [userLabel.text sizeWithFont:userLabel.font constrainedToSize:[tableView frame].size lineBreakMode:NSLineBreakByWordWrapping];

See NSString UIKit Additions Reference.

EDIT:

I just tried this code:

NSLog (@"test: %@", NSStringFromCGSize([@"test" sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f]]));
NSLog (@"longer test: %@", NSStringFromCGSize([@"longer test" sizeWithFont:[UIFont fontWithName:@"Arial" size:18.0f]]));

and result is:

test: {30, 22}
longer test: {85, 22}

CGSize is a struct:

struct CGSize {
   CGFloat width;
   CGFloat height;
};
typedef struct CGSize CGSize;

So you're probably looking at size.height instead of size.width

EDIT2:

from documentation sizeWithFont:forWidth:lineBreakMode:

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.

So you'll be better of defining a maximum size (real width and a big height) and go with the:

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

Please see this answer.




回答2:


I think it is easier this way. After setting the "text" property of the userLabel, call this method.

[userLabel sizeToFit];

At this point, the userLabel.frame has been changed so that it fits the text with the selected font. You can use userLabel.frame.size.height to adjust your table view cell.



来源:https://stackoverflow.com/questions/13304823/sizewithfont-always-returns-the-same-value-no-matter-what-string-is-used

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