Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Created March 5, 2014 17:48
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save brennanMKE/9372502 to your computer and use it in GitHub Desktop.
Save brennanMKE/9372502 to your computer and use it in GitHub Desktop.
Text Height in Objective-C for NSString and NSAttributedString
- (CGFloat)heightForAttributedString:(NSAttributedString *)text maxWidth:(CGFloat)maxWidth {
if ([text isKindOfClass:[NSString class]] && !text.length) {
// no text means no height
return 0;
}
NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGSize size = [text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:options context:nil].size;
CGFloat height = ceilf(size.height) + 1; // add 1 point as padding
return height;
}
- (CGFloat)heightForString:(NSString *)text font:(UIFont *)font maxWidth:(CGFloat)maxWidth {
if (![text isKindOfClass:[NSString class]] || !text.length) {
// no text means no height
return 0;
}
NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
NSDictionary *attributes = @{ NSFontAttributeName : font };
CGSize size = [text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:options attributes:attributes context:nil].size;
CGFloat height = ceilf(size.height) + 1; // add 1 point as padding
return height;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment