UITextField set cursor to start text position

I need to move the cursor to start a text position in order to set focus on the text field. Is it possible to do this?

+15
ios objective-c uitextfield
Apr 10 '13 at
source share
3 answers

Set the view controller (or some other appropriate object) as the delegate text field and implement the textFieldDidBeginEditing: method as follows:

 - (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 is implemented by UITextField ), so you will not find it directly in the UITextField documentation.

+20
Apr 10 '13 at 16:27
source share
 self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos]; 

Check Search for cursor position in UITextField

+2
Apr 10 '13 at 16:24
source share

If someone is looking for an answer in Swift:

 let desiredPosition = textField.beginningOfDocument textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition) 

But I believe that this only works if the cursor is already in the text box. You can use this for this:

 textField.becomeFirstResponder() let desiredPosition = textField.beginningOfDocument textField.selectedTextRange = textField.textRangeFromPosition(desiredPosition, toPosition: desiredPosition) 
+2
Jan 27 '16 at 23:10
source share



All Articles