Moving the cursor to the beginning of UITextField

10,400

Solution 1

UITextField conforms to the UITextInput protocol, which provides methods that let you control the selected range. This works in my testing:

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.selectedTextRange = [textField
        textRangeFromPosition:textField.beginningOfDocument
        toPosition:textField.beginningOfDocument];
}

Solution 2

You're fighting the system on this one. UITextField does not have any public properties to set the cursor position (which actually correlates to the beginning of the current selection). If you can use a UITextView instead, the following delegate methods will force the cursor to the beginning of the text. Just be aware that users won't expect this behavior and you should double-check your motives for wanting to do it.

- (void)textViewDidBeginEditing:(UITextView *)textView {
    shouldMoveCursor = YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    if(shouldMoveCursor)
    {
        NSRange beginningRange = NSMakeRange(0, 0);
        NSRange currentRange = [textView selectedRange];
        if(!NSEqualRanges(beginningRange, currentRange))
            [textView setSelectedRange:beginningRange];
        shouldMoveCursor = NO;
    }
}

Where shouldMoveCursor is a BOOL variable you maintain in your controller.

Solution 3

works for me

// Get current selected range , this example assumes is an insertion point or empty selection
UITextRange *selectedRange = [textField selectedTextRange];
// Calculate the new position, - for left and + for right
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:3];
// Construct a new range using the object that adopts the UITextInput, our textfield
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:newPosition];
// Set new range
[textField setSelectedTextRange:newRange];
Share:
10,400
Justin Galzic
Author by

Justin Galzic

Updated on July 27, 2022

Comments

  • Justin Galzic
    Justin Galzic almost 2 years

    Is there a way to make the cursor be at the start of a UITextField?

    When I display the control with content, the cursor is placed at the end of the text. I'd like to move it to the beginning.

  • anshul
    anshul about 12 years
    Hey warrenm, thaks buddy. This code is just awesome man. Hats off to you.
  • Rizwan Ahmed
    Rizwan Ahmed almost 8 years
    This solution works great ! Make sure you conform to UITextField delegate protocol. :)