【问题标题】:Getting cursor position in a UITextView on the iPhone?在 iPhone 上的 UITextView 中获取光标位置?
【发布时间】:2023-03-14 07:58:02
【问题描述】:

我们的 iPhone 应用中有一个 UITextView,它是可编辑的。当用户按下一些工具栏按钮时,我们需要在光标位置插入一些文本,但似乎找不到找到光标当前位置的文档(或未文档)方法。

有没有人有任何想法或其他人有类似的成就?

【问题讨论】:

  • 值得注意的是,如果在 textViewDidBeginEditing:textField 中请求, textField.selectedRange.location 将不会返回位置,除非您在延迟后得到它。

标签: iphone uitextview


【解决方案1】:

Swift 4

// lets be safe, thus if-let
if let cursorPosition = textView.selectedTextRange?.start {
    // cursorPosition is a UITextPosition object describing position in the text

    // if you want to know its position in textView in points:
    let caretPositionRect = textView.caretRect(for: cursorPosition)
}

我们只是使用textView.selectedTextRange 来获取选定的文本范围,光标位置在其start 位置。

【讨论】:

  • 谢谢,我不知道caretRect
【解决方案2】:

当文本视图是第一响应者时,使用UITextView selectedRange 属性查找插入点。否则,当视图不在焦点上时,此属性返回NSNotFound。如果您需要在这种情况下知道光标位置,请考虑继承 UITextView 并覆盖 canResignFirstResponder 方法,您可以将光标位置存储到成员变量中。

【讨论】:

  • 这是很容易错过的重要信息。我无法告诉你我花了多长时间才弄清楚为什么 selectedRange.location 会返回 NSNotFound。您可以使用以下方法检查无效位置: if (myTextField.selectedRange.location == NSNotFound)
  • 你解决了我的生活!但现在我想知道,selectedTextRange 是什么意思?使用它时我总是得到整个文本的开头...
【解决方案3】:

你试过UITextView.selectedRange吗?它返回一个NSRange,它的位置元素应该告诉你光标在哪里。

【讨论】:

    【解决方案4】:

    就像drawh说的,你可以使用UITextView的selectedRange来返回插入点。此范围的长度始终为零。下面的例子展示了如何做到这一点。

    NSString *contentsToAdd = @"some string";
    NSRange cursorPosition = [tf selectedRange];
    NSMutableString *tfContent = [[NSMutableString alloc] initWithString:[tf text]];
    [tfContent insertString:contentsToAdd atIndex:cursorPosition.location];
    [theTextField setText:tfContent];
    [tfContent release];
    

    【讨论】:

    • 请注意,在 iPhone 3.0 中,范围的长度不再总是为零。如果用户选择了文本,则长度将非零。在这种情况下,您可能需要使用 replaceCharactersInRange:withString: 而不是 insertString::atIndex:。您还应该适当地设置新的选择范围。
    • 这很好——但是当我这样做时,用户的光标会被抛到 UITextView 的末尾。如何将用户的光标保持在原位?
    • 杰森,试试 tf.selectedRange = NSMakeRange(cursorPosition.location + contentsToAdd.length, 0);设置新文本后
    猜你喜欢
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多