Programmatically Select all text in UITextField

Thats what did the trick for me:

[self.titleField setSelectedTextRange:[self.titleField textRangeFromPosition:self.titleField.beginningOfDocument toPosition:self.titleField.endOfDocument]];

Pretty ugly but it works, so there will be no sharedMenuController shown!

To fix the "only works every second time" problem use following:

__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    __strong __typeof(weakSelf) strongSelf = weakSelf;
    UITextRange *range = [strongSelf textRangeFromPosition:strongSelf.beginningOfDocument toPosition:strongSelf.endOfDocument];
    [strongSelf setSelectedTextRange:range];
});

Thanks to Eric Baker ( just edited from comment in here )


Turns out, calling -selectAll: with a non-nil sender displays the menu. Calling it with nil causes it to select the text, but not display the menu.

I tried this after my bug report about it came back from Apple with the suggestion that I pass nil instead of self.

No need to muck with UIMenuController or other selection APIs.


I just tested this to verify Mirko's comment above, but my test verifies that selectAll: does in fact select all the text when it's sent to the UITextField itself.

Note that the text will be immediately obscured with CUT | COPY | PASTE actions, but to your question, it is exactly what appears when a user taps "Select All" to begin with.

The solution I'm going with follows, note that the second line will temporarily hide the CUT/COPY/PASTE dialog, without disabling it for explicit user selections

[_myTextField selectAll:self];
[UIMenuController sharedMenuController].menuVisible = NO;

Use what you need

ObjC

[yourtextField becomeFirstResponder]; //puts cursor on text field
[yourtextField selectAll:nil];  //highlights text
[yourtextField selectAll:self]; //highlights text and shows menu(cut copy paste)

Swift

yourTextField.becomeFirstResponder() //puts cursor on text field
yourTextField.selectAll(nil)  //highlights text
yourTextField.selectAll(self) //highlights text and shows menu(cut copy paste)

This is the best solution I've found. No sharedMenuController, and it works consecutively:

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [textField performSelector:@selector(selectAll:) withObject:nil afterDelay:0.1];
}