Skip to content

Instantly share code, notes, and snippets.

@stuartjmoore
Created March 15, 2014 18:18
Show Gist options
  • Save stuartjmoore/9571615 to your computer and use it in GitHub Desktop.
Save stuartjmoore/9571615 to your computer and use it in GitHub Desktop.
- (CGFloat)heightThatFits {
if(!self.text || [self.text isEqualToString:@""])
return 0;
if([self respondsToSelector:@selector(attributedText)]) {
CGSize maxSize = (CGSize){ self.frame.size.width, MAXFLOAT };
CGRect frame = [self.attributedText boundingRectWithSize:maxSize
options:(NSStringDrawingUsesLineFragmentOrigin|
NSStringDrawingUsesFontLeading)
context:nil];
return ceilf(frame.size.height);
} else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_6_0
#warning No more iOS 5? Remove me!
#endif
CGSize maxSize = (CGSize){ self.frame.size.width, MAXFLOAT };
CGSize size = [self.text sizeWithFont:self.font
constrainedToSize:maxSize
lineBreakMode:self.lineBreakMode];
return ceilf(size.height);
}
}
- (CGFloat)heightThatFits {
if(!self.text || [self.text isEqualToString:@""])
return 0;
if([self respondsToSelector:@selector(textContainer)]) {
[self.layoutManager ensureLayoutForTextContainer:self.textContainer];
[self layoutIfNeeded];
CGFloat height = [self.layoutManager usedRectForTextContainer:self.textContainer].size.height;
height += self.textContainerInset.top + self.textContainerInset.bottom;
return ceilf(height);
} else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
#warning No more iOS 6? Remove me!
#endif
CGFloat height = self.contentSize.height;
height += (self.contentInset.top + self.contentInset.bottom);
return ceilf(height);
}
}
#pragma mark -
- (CGFloat)maxHeight {
return 8192;
}
- (CGFloat)closestMaxHeight {
__block CGFloat height = self.maxHeight;
CGPoint point = CGPointMake(0, self.maxHeight);
NSUInteger glyphIndex = [self.layoutManager glyphIndexForPoint:point inTextContainer:self.textContainer];
NSUInteger charIndex = [self.layoutManager characterIndexForGlyphAtIndex:glyphIndex];
NSRange range = NSMakeRange(0, charIndex);
NSStringEnumerationOptions options = (NSStringEnumerationByParagraphs|NSStringEnumerationReverse);
NSStringEnumerationBlock block = ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
*stop = YES;
NSUInteger glyphIndex = [self.layoutManager glyphIndexForCharacterAtIndex:substringRange.location];
CGRect lineRect = [self.layoutManager lineFragmentRectForGlyphAtIndex:glyphIndex effectiveRange:NULL];
height = floorf(lineRect.origin.y);
};
[self.text enumerateSubstringsInRange:range options:options usingBlock:block];
return ceilf(height);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment