Getting the line number of the line that the caret is in in uitextview

Is it possible to get the line number of the current edit line of the UITextView.

  • Lines can be broken automatically.
  • User can enter a new line character

I've seen a lot of problems where people calculate the number of lines in text form, but none of them calculate the number of lines to carriage.

To get the total row count, you can use the following:

CGFloat numLines = self.contentSize.height/self.font.lineHeight;
NSLog(@"Total lines: %f", numLines);

      

But if I touch the middle of the text, I want to get the line number line I am activating for editing.

I also know that we can get the position of the caret in terms of x and y coordinates such as soo:

CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin;
NSLog(@"cursor start: %@", NSStringFromCGPoint(cursorPosition));

      

Any smart ideas?

+3


source to share


2 answers


How about selectedTextRange

? If its length is 0, you are looking at the location of the caret. After that, you can enumerateLines…

until you find the range containing the caret position.



+1


source


Don't you need it?

int currentLine = (int)(cursorPosition.y / self.font.lineHeight);

      



You may need +1 for the account to be right at the top of the line, you will have to try.

0


source







All Articles