Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
ArisRS Avatar asked Apr 10 '13 16:04

ArisRS


3 Answers

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.

like image 128
omz Avatar answered Oct 07 '22 23:10

omz


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

Check this Finding the cursor position in a UITextField

like image 25
Anoop Vaidya Avatar answered Oct 07 '22 23:10

Anoop Vaidya


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)
like image 45
Dave G Avatar answered Oct 08 '22 01:10

Dave G