在文本字段中插入一个字符后启用完成按钮:textFieldDidEndEditing:或textFieldShouldBeginEditing:或?

当用户在uitextfield中写入至少一个字符时,我想在导航栏上启用完成按钮(在模式视图中)。 我试过了:

  • textFieldDidEndEditing:当前一个uitextfield重新响应第一个响应者时启用该按钮(所以在当前uitextfield中使用零个字符)。
  • textFieldShouldBeginEditing:当文本字段成为第一个响应者时调用。 还有另一种方法吗?

[编辑]

解决方案可能是

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

但都没有

  [self.navigationItem.rightBarButtonItem setEnabled:YES]; 

要么

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

工作。

正确的代码是;

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

编辑 :正如MasterBeta之前和David Lari之后正确指出的那样,该事件应该响应Editing Changed。 我正在用David Lari的解决方案更新答案,因为这是标记为正确的解决方案。

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

但是当用户按下文本字段控件的清除按钮时,不会调用shouldChangeCharactersInRange 。 当文本字段为空时,也应禁用您的按钮。

IBAction可以与文本字段控制的编辑更改事件相关联。 当用户输入或按清除按钮时将调用它。

 - (IBAction) editDidChanged: (id) sender { if (((UITextField*)sender).text.length > 0) { [yourButton setEnabled:YES]; } else { [yourButton setEnabled:NO]; } } 

@MasterBeta:差不多正确。 按照他的说明将操作连接到编辑已更改 ,但此代码更简单,没有拼写错误:

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

实际上,在Xcode 6.x中足以标记ON自动启用返回键

这个答案似乎适用于所有情况。 单一字符,清晰和所有变化。 希望有人觉得这很有帮助。

斯威夫特2.2

您可以将自定义方法“checkTextField()”分配给“myTextField”UITextField,如下所示:

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

并在方法内切换完成按钮:

 func checkTextField(sender: UITextField) { doneButton.enabled = !sender.hasText(); } 

不需要任何代表。

试着去:

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

}

当下面的’w4nderlust’存在更好的解决方案时,这个答案被标记为正确。 这个答案是他们的,让他们信用!