Enabling done button after inserting one char in a

2019-02-01 23:53发布

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.

7条回答
欢心
2楼-- · 2019-02-02 00:13

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!

查看更多
在下西门庆
3楼-- · 2019-02-02 00:18

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

查看更多
Ridiculous、
4楼-- · 2019-02-02 00:20

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

查看更多
女痞
5楼-- · 2019-02-02 00:21

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];
    }
}
查看更多
The star\"
6楼-- · 2019-02-02 00:26

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

}
查看更多
劳资没心,怎么记你
7楼-- · 2019-02-02 00:27

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.

查看更多
登录 后发表回答