当用户在uitextfield中写入至少一个字符时,我想在导航栏上启用完成按钮(在模式视图中)。我试过了:
[编辑]
解决方案可能是
-(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
的工作。
答案 0 :(得分:32)
正确的代码是;
-(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;
}
答案 1 :(得分:3)
@MasterBeta:差不多正确。按照他的说明将操作连接到编辑已更改,但此代码更简单且没有拼写错误:
- (IBAction)editingChanged:(UITextField *)textField
{
//if text field is empty, disable the button
_myButton.enabled = textField.text.length > 0;
}
答案 2 :(得分:1)
实际上,在Xcode 6.x中足以标记ON自动启用返回键
答案 3 :(得分:0)
This答案似乎适用于所有情况。单一字符,清晰和所有变化。希望有人觉得这很有帮助。
答案 4 :(得分:0)
Swift 2.2
您可以将自定义方法“checkTextField()”分配给“myTextField”UITextField:
myTextField.addTarget(self, action: #selector(self.checkTextField(_:)), forControlEvents: .EditingChanged);
并将方法内的完成按钮切换为:
func checkTextField(sender: UITextField) {
doneButton.enabled = !sender.hasText();
}
无需任何代表。
答案 5 :(得分:-2)
试着继续:
-(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'存在更好的解决方案时,这个答案被标记为正确。这个答案是他们的,让他们信用!