Skip to content

Commit

Permalink
[TextControls] Fix line counting mechanism in text areas
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 319816916
  • Loading branch information
andrewoverton authored and material-automation committed Jul 6, 2020
1 parent b4ceacb commit b919fad
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions components/TextControls/src/BaseTextAreas/MDCBaseTextArea.m
Original file line number Diff line number Diff line change
Expand Up @@ -285,14 +285,24 @@ - (void)layoutGradientLayers {
}

- (CGFloat)numberOfLinesOfText {
CGSize fittingSize = CGSizeMake(CGRectGetWidth(self.textView.bounds), CGFLOAT_MAX);
NSDictionary *attributes = @{NSFontAttributeName : self.textView.font};
CGRect boundingRect =
[self.textView.text boundingRectWithSize:fittingSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
return MDCRound(CGRectGetHeight(boundingRect) / self.normalFont.lineHeight);
// For more context on measurinig the lines in a UITextView see here:
// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/TextLayout/Tasks/CountLines.html
NSLayoutManager *layoutManager = self.textView.layoutManager;
NSUInteger numberOfGlyphs = layoutManager.numberOfGlyphs;
NSRange lineRange = NSMakeRange(0, 1);
NSUInteger index = 0;
NSUInteger numberOfLines = 0;
while (index < numberOfGlyphs) {
[layoutManager lineFragmentRectForGlyphAtIndex:index effectiveRange:&lineRange];
index = NSMaxRange(lineRange);
numberOfLines += 1;
}

if (self.textView.text.length > 0 &&
[self.textView.text characterAtIndex:self.textView.text.length - 1] == '\n') {
numberOfLines += 1;
}
return (CGFloat)numberOfLines;
}

- (CGFloat)numberOfLinesOfVisibleText {
Expand Down

0 comments on commit b919fad

Please sign in to comment.