ios UITextField 设置光标开始文本位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15931227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UITextField set cursor to start text position
提问by RomanS
I need to move cursor to start text position on set focus on the textfield. Is it possible tot do?
我需要移动光标以在文本字段上设置焦点时开始文本位置。有可能吗?
回答by omz
Set your view controller (or some other appropriate object) as the text field's delegate
and implement the textFieldDidBeginEditing:
method like this:
将您的视图控制器(或其他一些适当的对象)设置为文本字段delegate
并实现如下textFieldDidBeginEditing:
方法:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
UITextPosition *beginning = [textField beginningOfDocument];
[textField setSelectedTextRange:[textField textRangeFromPosition:beginning
toPosition:beginning]];
}
Note that setSelectedTextRange:
is a protocol method of UITextInput
(which UITextField
implements), so you won't find it directly in the UITextField
documentation.
请注意,这setSelectedTextRange:
是UITextInput
(UITextField
实现)的协议方法,因此您不会直接在UITextField
文档中找到它。
回答by Anoop Vaidya
self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
Check this Finding the cursor position in a UITextField
回答by Dave G
If anyone's looking for the answer in Swift:
如果有人在 Swift 中寻找答案:
let desiredPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)
But I believe this only works if the cursor is already in the text field. You can use this to do that:
但我相信这只适用于光标已经在文本字段中的情况。你可以用它来做到这一点:
textField.becomeFirstResponder()
let desiredPosition = textField.beginningOfDocument
textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)