Get the NSString height in iOS 7

mahavir picture mahavir · Feb 25, 2014 · Viewed 16.9k times · Source

I am using the below code to calculate the height of a label from string length. Im using xcode 5.0 and it works fine in iOS 6 simulator but it's not working well in iOS 7.

NSString* str = [[array objectAtIndex:i]valueForKey:@"comment"];

CGSize size = [className sizeWithFont:[UIFont systemFontOfSize:15]   
 constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];

Height_1 = size.height;

If there is any solution for iOS 7 then please help. Thanks in Advance

Answer

Pratik Mistry picture Pratik Mistry · Feb 25, 2014

Well here is a solution I use for calculating the height for iOS 6 and iOS 7, and I have passed few arguments to make it reusable.

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

/**
*  This method is used to calculate height of text given which fits in specific width having    font provided
*
*  @param text       Text to calculate height of
*  @param widthValue Width of container
*  @param font       Font size of text
*
*  @return Height required to fit given text in container
*/

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
{
    CGFloat result = font.pointSize + 4;
    if (text)
    {
        CGSize textSize = { widthValue, CGFLOAT_MAX };       //Width and height of text area
        CGSize size;
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
        {
            //iOS 7
            CGRect frame = [text boundingRectWithSize:textSize
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{ NSFontAttributeName:font }
                                          context:nil];
            size = CGSizeMake(frame.size.width, frame.size.height+1);
        }
        else
        {
            //iOS 6.0
            size = [text sizeWithFont:font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
        }
        result = MAX(size.height, result); //At least one row
    }
    return result;
}

Hope this helps and yes any suggestions are appreciated. Happy Coding :)

For iOS 7 and above use below method.

+ (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
    CGSize size = CGSizeZero;
    if (text) {
        //iOS 7
        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height + 1);
    }
    return size;
}