简体   繁体   English

UITextField将光标设置为开始文本位置

[英]UITextField set cursor to start text position

I need to move cursor to start text position on set focus on the textfield. 我需要移动光标以在文本字段上的设置焦点上开始文本位置。 Is it possible tot do? 有可能吗?

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:UITextInputUITextField实现的)的协议方法,因此您不会直接在UITextField文档中找到它。

self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];

选中此项在UITextField中查找光标位置

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM