如何将UITextView的光标移动到TOUCHED LOCATION?

时间:2013-12-18 16:39:18

标签: ios iphone uitextview

我的问题的目标是制作iOS应用笔记应用。 iOS笔记应用程序的重点是它们为用户提供使用超链接或电话号码链接或电子邮件地址作为蓝色文本颜色,我们可以同时编辑文本。

通常,当我们按下UITextView时,它会将光标定位到我们触摸的位置。但如果我使用UITextView的dataDetectorTypes来输入像iOS的笔记应用程序这样的电话号码或http链接,我应该将其设置为不可编辑,否则链接不起作用。 这意味着我无法单击UITextView和编辑文本。

但我可以使用下面的代码将其设置为可编辑

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

-

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

现在我可以编辑文本,一切正常,但问题是它总是从文本结束开始,因此用户应该再次点击他们想要写的地方。我理解其中的原因。

现在我想将光标移动到我在第一点按下的位置,然后使用[aRecognizer locationInView:view]获得坐标;

如何将UITextView中的游标移动到位置我从识别器中获取?

感谢。

2 个答案:

答案 0 :(得分:9)

- (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]];
    }
}

答案 1 :(得分:1)

Swift 4中的答案:

tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.textViewTapped(recognizer:)))
textView.addGestureRecognizer(tapGesture)

@objc func textViewTapped(recognizer: UITapGestureRecognizer) {
    if recognizer.state == .ended {     
        textView.isEditable = true
        textView.becomeFirstResponder()

        let location = recognizer.location(in: textView)
        if let position = textView.closestPosition(to: location) {
            let uiTextRange = textView.textRange(from: position, to: position)

            if let start = uiTextRange?.start, let end = uiTextRange?.end {
                let loc = textView.offset(from: textView.beginningOfDocument, to: position)
                let length = textView.offset(from: start, to: end)

                textView.selectedRange = NSMakeRange(loc, length)

            }
        }
    }
}