Bright Lee Bright Lee -4 years ago 134
iOS Question

How to move cursor of UITextView to TOUCHED LOCATION?

The goal of my question is making note app like iOS's.
The point of iOS's note app is that they provide to user to use hyper link or phone number link or email address as blue textcolor, and we can edit text at the same time.

Normally, When we press UITextView, it locate cursor to where we touched. but If I'm using dataDetectorTypes of UITextView to put things like phone number or http links like iOS's note app, I should set it non-editable, otherwise link doesn't work.
It means I can't click UITextView and Edit text.

but I could set it editable by using code below

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(editTextRecognizerTabbed:)];


-

- (BOOL) editTextRecognizerTabbed:(UITapGestureRecognizer *) aRecognizer
{
textview.editable = YES;
textview.dataDetectorTypes = UIDataDetectorTypeNone;
[textview becomeFirstResponder];
}


and now I could edit text and everything works fine, but problem is that it always start end of text, so user should tap once again to where they want to write. and I understand the reason.

NOW I want to move cursor to location where I pressed at the first point and I got the coordinate by using [aRecognizer locationInView:view];

SO HOW TO MOVE CURSOR in UITextView TO LOCATION I GOT FROM RECOGNIZER?

Thanks.

Answer Source
- (void) editTextRecognizerTabbed:(UITapGestureRecognizer *) aRecognizer
{
    if (aRecognizer.state==UIGestureRecognizerStateEnded)
    {
        //Not sure if you need all this, but just carrying it forward from your code snippet
        textview.editable = YES;
        textview.dataDetectorTypes = UIDataDetectorTypeNone;
        [textview becomeFirstResponder];

        //Consider replacing self.view here with whatever view you want the point within
        CGPoint point = [aRecognizer locationInView:self.view];
        UITextPosition * position=[textView closestPositionToPoint:point];
        [textView setSelectedTextRange:[textView textRangeFromPosition:position toPosition:position]];
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download