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

☆樱花仙子☆ 提交于 2019-11-30 02:05:56

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;
}

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];
    }
}

@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;

}

Actually, in Xcode 6.x is sufficient to flag in ON Auto-enable Return Key

Abdullah Umer

This answer seems to be working in all scenarios. Single character, clear and all changes. Hope someone finds this helpful.

Swift 2.2

You can assign custom method "checkTextField()" to "myTextField" UITextField as:

myTextField.addTarget(self, action: #selector(self.checkTextField(_:)), forControlEvents: .EditingChanged);

and toggle the done button inside the method as:

func checkTextField(sender: UITextField) {

    doneButton.enabled = !sender.hasText();
}

No need of any delegate.

try and go with:

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

}

This answer was marked correct when infact a better solution existed by 'w4nderlust' below. This answer is theirs, let them take the credit!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!