Reputation: 6119
I'm using the following method:
- (void)textViewDidChange:(UITextView *)textView {
int numLines = self.textInputView.contentSize.height/self.textInputView.font.lineHeight;
NSLog(@"number of lines is %i", numLines);
}
This returns the line count mostly correctly except for a few edge cases.
The problem is that when I press the "Return
" key on the keyboard, a new blank line is started in the textView, but the line count does not account for this. After you type the first character, it will be counted. It also does not give the correct count when backspacing, up until you delete or add a single character on the previous line.
Is there a way to accurately get line count? Thanks
Upvotes: 0
Views: 250
Reputation: 9553
This is not a stable way to get the number of lines. The ‘lineHeight’ of a font isn’t always what the textView will use as its line height.
Instead, get the UITextView’s
layoutManager
, and step through the runs of text in the layoutManager using:
- (CGRect)lineFragmentRectForGlyphAtIndex:(NSUInteger)glyphIndex effectiveRange:(NSRangePointer)effectiveGlyphRange;
If you call that method in a loop, stating at glyphIndex 0 and each time pass the end of the previous effectiveGlyphRange as the new glyphIndex, you’ll be given the rectangles of all the text that’s been laid out, one after the other. You won’t want to just count how many there are, because there CAN be multiples per line, but you can piece together how many lines you have from that information.
There should be an easier way, I know. And maybe there is and I never learned it!
Upvotes: 1