Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling done button after inserting one char in a textfield: textFieldDidEndEditing: or textFieldShouldBeginEditing: or?

I would like to enable the done button on the navbar (in a modal view) when the user writes at least a char in a uitextfield. I tried:

  • textFieldDidEndEditing: enables the button when the previous uitextfield resigns first responder (so with the zero chars in the current uitextfield).
  • textFieldShouldBeginEditing: is called when the textfield becomes the first responder. Is there another way to do this?

[EDIT]

The solution could be

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

but neither

 [self.navigationItem.rightBarButtonItem setEnabled:YES];

or

[doneButton setEnabled:YES]; //doneButton is an IBOutlet tied to my Done UIBarButtonItem in IB

work.

like image 914
Sefran2 Avatar asked Feb 25 '11 13:02

Sefran2


3 Answers

But shouldChangeCharactersInRange won't be called when user press clear button of text field control. And your button should also be disabled when text field is empty.

A IBAction can be connected with Editing Changed event of text field control. And it will be called when users type or press clear button.

- (IBAction) editDidChanged: (id) sender {
    if (((UITextField*)sender).text.length > 0) {
        [yourButton setEnabled:YES];
    } else {
        [yourButton setEnabled:NO];
    }
}
like image 104
MasterBeta Avatar answered Oct 21 '22 08:10

MasterBeta


The correct code is;

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger length = editingTextField.text.length - range.length + string.length;
    if (length > 0) {
        yourButton.enabled = YES;
    } else { 
        yourButton.enabled = NO;
    }
    return YES;
}

Edit: As correctly pointed out by MasterBeta before and David Lari later, the event should respond to Editing Changed. I'm updating the answer with David Lari's solution as this was the one marked as correct.

- (IBAction)editingChanged:(UITextField *)textField
{
   //if text field is empty, disable the button
    _myButton.enabled = textField.text.length > 0;
}
like image 25
w4nderlust Avatar answered Oct 21 '22 08:10

w4nderlust


@MasterBeta: Almost correct. Follow his instructions to connect an action to Editing Changed, but this code is simpler and has no typos:

- (IBAction)editingChanged:(UITextField *)textField
{
   //if text field is empty, disable the button
    _myButton.enabled = textField.text.length > 0;

}
like image 39
David Lari Avatar answered Oct 21 '22 07:10

David Lari