Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Select all text in UITextField

How can I programmatically select all text in UITextField?

like image 285
Mirko Avatar asked Nov 06 '09 19:11

Mirko


2 Answers

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 )

like image 175
blackforestcowboy Avatar answered Nov 15 '22 07:11

blackforestcowboy


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.

like image 21
Rick Avatar answered Nov 15 '22 08:11

Rick