UITextField set cursor to start text position

寵の児 提交于 2019-12-18 03:17:26

问题


I need to move cursor to start text position on set focus on the textfield. Is it possible tot do?


回答1:


Set your view controller (or some other appropriate object) as the text field's delegate and implement the textFieldDidBeginEditing: method like this:

- (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.




回答2:


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

Check this Finding the cursor position in a UITextField




回答3:


If anyone's looking for the answer in 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)


来源:https://stackoverflow.com/questions/15931227/uitextfield-set-cursor-to-start-text-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!