Maniganda saravanan
Maniganda saravanan

Reputation: 2198

UITextview cursor moves to the end of the line

If i select a position in UITextview it place the cursor to end of the text (content).

i cant get the current position of where the user tap the textview.

Before click, when i click 6 in textviewenter image description here

After Click , cursor moves to end of the textview and shows like this

enter image description here

Upvotes: 0

Views: 1262

Answers (2)

Rafał Sroka
Rafał Sroka

Reputation: 40030

If you know the index of the cursor you can just call:

NSUInteger cursorLocation =  _textView.selectedRange.location;

You can also implement a UITapGestureRecognizer and handle it with:

- (void)textTapped:(UITapGestureRecognizer *)recognizer
{
    UITextView *textView = (UITextView *)recognizer.view;

    // Location of the tap in text-container coordinates
    NSLayoutManager *layoutManager = textView.layoutManager;
    CGPoint location = [recognizer locationInView:textView];

    location.x -= textView.textContainerInset.left;
    location.y -= textView.textContainerInset.top;

    // Find the character that's been tapped on
    NSUInteger tappedCharacterIndex;
    tappedCharacterIndex = [layoutManager characterIndexForPoint:location
                                                 inTextContainer:textView.textContainer
                        fractionOfDistanceBetweenInsertionPoints:NULL];
}

Upvotes: 0

Prince Agrawal
Prince Agrawal

Reputation: 3607

To know where the touch event occurred, implement this method in your viewController..

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

Now get the textView as touch object & place your cursor there.. I am just giving you a hint here.. Try to get a solution.. If there's any issue, let me know.. :)

Update:

If your textView is editable, you don't need to write any code there. Where ever you tap, cursor will appear automatically.

Yes, the code you are writing to change height of textView is affecting your tap & the cursor position..

Once you tap, textView is getting the touch rect, & then your method is being called. hence when the cursor is appearing, its appearing at same rect but different position with respect to textView. Let me know if more info is needed..

You can resize your textView after editing is done. This will solve your issue... :)

Upvotes: 1

Related Questions