I just wrap the text height calculate function to a category of NSString
.
In the .h
file:
@interface NSString (Additions)
- (CGSize)sizeWithFont:(UIFont *)font;
- (CGSize)sizeWithFontSize:(float)fSize constrainedToSize:(CGSize)cSize;
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)cSize;
@end
In the .m
file:
#import "NSString+Additions.h"
#define kSystemVersion ([[UIDevice currentDevice] systemVersion].intValue)
@implementation NSString (Additions)
- (CGSize)sizeWithFont:(UIFont *)font
{
return [self sizeWithFont:font constrainedToSize:(CGSize)
{MAXFLOAT, MAXFLOAT}];
}
- (CGSize)sizeWithFontSize:(float)fSize constrainedToSize:(CGSize)cSize
{
UIFont *font = [UIFont systemFontOfSize:fSize];
return [self sizeWithFont:font constrainedToSize:cSize];
}
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)cSize
{
if (kSystemVersion < 7)
{
CGSize size = [self sizeWithFont:font constrainedToSize:cSize
lineBreakMode:NSLineBreakByWordWrapping];
return size;
}
else
{
NSDictionary *stringAttributes = @{NSFontAttributeName:font};
CGRect rect = [self boundingRectWithSize:cSize
options:NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:stringAttributes
context:nil];
return rect.size;
}
}
@end
Then, just calculate the string's height in the place you want. such as:
CGSize cSize = (CGSize){THE_LABEL_WIDTH_HERE, MAXFLOAT};
NSString *tmpString = @"Hello there. I'm junkor, and you can call me jun.";
// will use the system font
float height = [tmpString sizeWithFontSize:15 constrainedToSize:cSize].height;
The height is what you want. Sometimes, when you calculate the size of the text, you can cache the size to the data entity, such as in the tableView
's delegate function:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
When you reload data or scroll the tableView
, it always calculates, makes a cache to the height (or size). Make sure you just calculate once for every text, it's better.