iosuitableviewsizewithfont

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


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


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.