Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top