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
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;
}
Try using this
#define FONT_SIZE 15.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 20.0f
NSString *text;
CGSize constraint;
CGSize size;
CGFloat height;
text = [[array objectAtIndex:i]valueForKey:@"comment"];
constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGRect textRect = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE]}
context:nil];
size = textRect.size;
height = size.height;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With