Skip to content

Instantly share code, notes, and snippets.

@annidy
Forked from brennanMKE/textHeight.m
Created May 22, 2019 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save annidy/dd36427f9190c91983b9776b882e6b0f to your computer and use it in GitHub Desktop.
Save annidy/dd36427f9190c91983b9776b882e6b0f 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