I need to move cursor to start text position on set focus on the textfield. Is it possible tot do?
Asked
Active
Viewed 2.6k times
3 Answers
22
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.
omz
- 52,865
- 5
- 126
- 139
-
I set this code but it dose not work for me and textfield's cursor dose not set at end of text. can help me? – Bita Oct 13 '20 at 07:26
4
self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
Check this Finding the cursor position in a UITextField
Anoop Vaidya
- 45,913
- 15
- 108
- 138
4
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)
Titouan de Bailleul
- 12,690
- 11
- 64
- 119
Dave G
- 11,732
- 7
- 54
- 81
-
when i use this code and select my cursor at first of text, cursor set at first but I don't want to that – Bita Oct 13 '20 at 07:30