Created
October 4, 2014 15:21
-
-
Save youngshook/d8e8475ad424160321ae to your computer and use it in GitHub Desktop.
Get UITextView measureHeight
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
| @interface UITextView (Helper) | |
| - (CGFloat)measureHeight; | |
| @end | |
| #import "UITextView+Helper.h" | |
| @implementation UITextView (Helper) | |
| - (CGFloat)measureHeight | |
| { | |
| if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)]) | |
| { | |
| // This is the code for iOS 7. contentSize no longer returns the correct value, so | |
| // we have to calculate it. | |
| // | |
| // This is partly borrowed from HPGrowingself, but I've replaced the | |
| // magic fudge factors with the calculated values (having worked out where | |
| // they came from) | |
| CGRect frame = self.bounds; | |
| // Take account of the padding added around the text. | |
| UIEdgeInsets textContainerInsets = self.textContainerInset; | |
| UIEdgeInsets contentInsets = self.contentInset; | |
| CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + self.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right; | |
| CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom; | |
| frame.size.width -= leftRightPadding; | |
| frame.size.height -= topBottomPadding; | |
| NSString *textToMeasure = self.text; | |
| if ([textToMeasure hasSuffix:@"\n"]) | |
| { | |
| textToMeasure = [NSString stringWithFormat:@"%@-", self.text]; | |
| } | |
| // NSString class method: boundingRectWithSize:options:attributes:context is | |
| // available only on ios7.0 sdk. | |
| NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; | |
| [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping]; | |
| NSDictionary *attributes = @{ NSFontAttributeName: self.font, NSParagraphStyleAttributeName : paragraphStyle }; | |
| CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT) | |
| options:NSStringDrawingUsesLineFragmentOrigin | |
| attributes:attributes | |
| context:nil]; | |
| CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding); | |
| return measuredHeight; | |
| } | |
| else | |
| { | |
| return self.contentSize.height; | |
| } | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment