Reputation: 1394
I need to move cursor to start text position on set focus on the textfield. Is it possible tot do?
Upvotes: 16
Views: 26555
Reputation: 12216
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)
Upvotes: 4
Reputation: 53561
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.
Upvotes: 23
Reputation: 46563
self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
Check this Finding the cursor position in a UITextField
Upvotes: 4