Search code examples
iosobjective-cuitextfielduitextfielddelegate

How to make UITextField select all first and then edit programatically?


I have a UITextField. On first click I want to select all the text programatically. So I called [textField selectAll:nil] in textFieldDidBeginEditing: delegate method. When I make a next click I want it to become normal editing mode. How to implement this programatically?.

Thanks in advance.


Solution

  • This prevents a popover from appearing, when the user taps on the selected text.

    To allow the first tap to always select all the text, and have the second tap deselect, keep your current code in the textFieldDidBeginEditing method, and extend UITextField to override canPerformAction:withSender:, to prevent the popover from appearing, like so:

    UITextField Subclass

    - (BOOL) canPerformAction:(SEL)action withSender:(id)sender {
        /* Prevent action popovers from showing up */
    
        if (action == @selector(paste:)
            || action == @selector(cut:)
            || action == @selector(copy:)
            || action == @selector(select:)
            || action == @selector(selectAll:)
            || action == @selector(delete:)
            || action == @selector(_define:)
            || action == @selector(_promptForReplace:)
            || action == @selector(_share:) )
        {
            //Get the current selection range
            UITextRange *selectedRange = [self selectedTextRange];
    
            //Range with cursor at the end, and selecting nothing
            UITextRange *newRange = [self textRangeFromPosition:selectedRange.end toPosition:selectedRange.end];
    
            //Set the new range
            [self setSelectedTextRange:newRange];
    
            return NO;
        } else {
            //Handle other actions?
        }
    
        return [super canPerformAction:action withSender:sender];
    }
    

    UITextFieldDelegate Methods

    //Select the text when text field receives focus
    - (void) textFieldDidBeginEditing:(UITextField *)textField
    {
        [textField selectAll:nil];
    }
    
    //Hide the keyboard when the keyboard "Done" button is pressed
    - (BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
    
        return TRUE;
    }
    

    I hope that helps!