selectall uitextfield does not always select all
Asked Answered
N

2

10
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [textField selectAll:self];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;    
}

In the above, the textField selects correctly but when I return from the keyboard and tap the textField for a second time consecutively, it does not select the text. If I do not pick it consecutively or if I deselect the text before returning from the keyboard, the next focus of that textField selects the text correctly.

How can I select the text in the abovementioned case?

Neoclassic answered 1/10, 2012 at 2:18 Comment(0)
M
10

I have found a perfect solution(invoke selectAll in next runloop):

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [textField performSelector:@selector(selectAll:) withObject:textField afterDelay:0.f];
}
Maudmaude answered 23/5, 2013 at 8:28 Comment(4)
Thanks, I'll test this when I canNeoclassic
You must be a genius! This is a bug on iOS 6 and 7, and I thought the only solution was to file a bug, and wait for a fix. Thanks!Inquisition
Filed a bug anyway: #15781101 "UITextField -selectAll: only works every other time".Inquisition
This still seems to be a bug as I tried both: textField.selectAll(nil) and textField.perform(#selector(UIResponder.selectAll(_:)), with: textField) and neither worked more than every other timeMetrology
T
3

I solved this issue using Grand Central Dispatch. You can wrap [textField selectAll:self]; with a dispatch_async call and dispatch_get_main_queue() as a first parameter.

    dispatch_async(dispatch_get_main_queue()){
        // ... code you want to run on the main queue goes here
    }
Twylatwyman answered 2/1, 2016 at 3:6 Comment(1)
Simple but important =)Lunn

© 2022 - 2024 — McMap. All rights reserved.