iOS-Get the NSString height in iOS 7

#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;
}

posted @ 2016-04-07 18:12  qike  阅读(171)  评论(0编辑  收藏  举报