Skip to content

Instantly share code, notes, and snippets.

@prat14k
Forked from brennanMKE/textHeight.m
Created December 29, 2017 06:48
Show Gist options
  • Save prat14k/c2c60526ef7b7bb14b5b5cca46e31e5c to your computer and use it in GitHub Desktop.
Save prat14k/c2c60526ef7b7bb14b5b5cca46e31e5c 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