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:
- (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.
self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
Check this Finding the cursor position in a UITextField
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With