Search code examples
ios6uitextfieldtext-alignment

iOS 6: UITextField textAlignment does not change cursor position


I use an instance of UITextField in which the text is normally aligned to the right, but switches to left alignment when being edited. This is done by calling setTextAlignment: on the editingDidBegin event. Since the update to iOS 6 this behaves strangely: The text alignment is changed correctly from right to left, but the cursor remains at the far right of the text field until some input is performed.

Does anybody know how to restore the expected behaviour so that the cursor moves as well when the alignment is changed?

To give some context: I use the text field to show a value with a unit. The unit is removed during editing and then displayed again after the user hits enter.

Method called on event editingDidBegin:

- (IBAction)textEditingDidBegin:(UITextField *)sender
{
    [sender setTextAlignment:NSTextAlignmentLeft];
    [sender setText:[NSString stringWithFormat:@"%.0f", width]];
}

Method called on event editingDidEnd:

- (IBAction)textEditingDidEnd:(id)sender
{
    [sender setTextAlignment:UITextAlignmentRight];
    [sender setText:[NSString stringWithFormat:@"%.0f m", width]];
}

Solution

  • -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
        textField.textAlignment = NSTextAlignmentLeft ;
        return YES ;
    }
    

    Change the textAlignment before editing did begin. The best place I know to do this is in the UITextFieldDelegate method textFieldShouldBeginEditing.