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)
Vla*_*rov 10
使用UITextView selectedRange
属性在文本视图为第一响应者时查找插入点.否则,当视图未处于焦点时,此属性将返回NSNotFound
.如果在这种情况下需要知道光标位置,请考虑子类化UITextView
和重写canResignFirstResponder
方法,您可以将光标位置存储到成员变量.
斯威夫特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
位置.
归档时间: |
|
查看次数: |
25317 次 |
最近记录: |