16

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

ArisRS
  • 1,362
  • 2
  • 19
  • 41

3 Answers3

23

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
  • 53,243
  • 5
  • 129
  • 141
  • 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
  • 46,283
  • 15
  • 111
  • 140
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,920
  • 11
  • 66
  • 121
Dave G
  • 12,042
  • 7
  • 57
  • 83
  • 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