Sizewithfont always returns the same value no matter which string is used

I want to calculate the height of a tableviewcell according to its text. I use

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 (font size). The strange thing is that when I use

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

everything is working fine. But I would prefer the first version, so I can easily adjust the width. Why doesn't it work?

Edit: sorry for the wrong naming convention, but userLabel is an NSString, not a label

+3
source share
2 answers

sizeWithFont is an NSString method (UIKit add-ons). Application:

 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 the NCCtring UIKit Add-ons Help .

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 the result:

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

CGSize is a struct :

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

So you are probably looking at size.height instead of size.width

EDIT2:

from the documentation sizeWithFont: forWidth: lineBreakMode:

If the line size exceeds the specified width, this method truncates the text (for layout purposes only), using the specified line interrupt mode until it matches the maximum width; it returns the size of the resulting truncated string.

So, you better determine the maximum size (real width and large height ) and go with:

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

See this answer .

+3
source

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

 [userLabel sizeToFit]; 

At this point, userLabel.frame has been modified so that it matches the text with the selected font. You can use userLabel.frame.size.height to customize the table view cell.

0
source

All Articles