在iPhone上的UITextView中获取光标位置?

use*_*686 28 iphone uitextview

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

有没有人有任何想法或有其他人有类似的东西吗?

小智 32

像drewh说的那样,你可以使用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];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,对于iPhone 3.0,范围的长度始终为零不再是真的.如果用户选择了文本,则长度将为非零.在这种情况下,您可能希望使用replaceCharactersInRange:withString:而不是insertString :: atIndex:.您还应该适当地设置新的选择范围. (6认同)
  • 杰森,试试tf.selectedRange = NSMakeRange(cursorPosition.location + contentsToAdd.length,0); 设置新文本后 (2认同)

Vla*_*rov 10

使用UITextView selectedRange属性在文本视图为第一响应者时查找插入点.否则,当视图未处于焦点时,此属性将返回NSNotFound.如果在这种情况下需要知道光标位置,请考虑子类化UITextView和重写canResignFirstResponder方法,您可以将光标位置存储到成员变量.


dre*_*ewh 8

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


Mil*_*sáľ 6

斯威夫特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)
}
Run Code Online (Sandbox Code Playgroud)

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