Search code examples
objective-ciosxcode4uitextfieldselectall

iOS: UITextField selectAll + Editing Did Begin not working


I'm trying to make the text in a UITextField select when the user taps the field to begin editing. The idea is that normally, they will want to erase the entire field first, so this saves the step of having to double tap and select all.

.h

- (IBAction)urlEditingDidBegin: (id)sender;

.m

- (IBAction)urlEditingDidBegin:(id)sender
{
    NSLog(@"Select Contents");

    [sender setText:@"Why isn't this working"];
    [sender selectAll:self];
}

In interface builder I wired my UITextField's "Editing Did Begin" event to the file's owner and connected it to my urlEditingDidBegin method.

When I tap the UITextField, the text in the field changes to "Why isn't this working" which proves the method is firing and that the sender is correct, however the text does not select.

What am I doing wrong?


Solution

  • Generally, if you want to give the user an easy way to clear the text add a clear by setting the clear button to "Appears while editing" in the xib or by calling

    [textField setClearButtonMode:UITextFieldViewModeWhileEditing];

    Selecting the text programmatically sounds tempting, but I think you are going to run into more problems, as it tends to open the editing menu for instance.