-
-
Save tobitech/b27c555ea8808dc64cb2ed6724933395 to your computer and use it in GitHub Desktop.
Text Height in Objective-C for NSString and NSAttributedString
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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