在文本字段中插入一个字符后启用完成按钮:textFieldDidEndEditing:或textFieldShouldBeginEditing:或? [英] Enabling done button after inserting one char in a textfield: textFieldDidEndEditing: or textFieldShouldBeginEditing: or?

查看:83
本文介绍了在文本字段中插入一个字符后启用完成按钮:textFieldDidEndEditing:或textFieldShouldBeginEditing:或?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:当前一个uitextfield重新响应第一个响应者时启用该按钮(所以在当前uitextfield中使用零个字符)。 / li>
  • 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

work。

推荐答案

正确的代码是;

-(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的解决方案更新答案,因为这是标记为正确的答案。

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

这篇关于在文本字段中插入一个字符后启用完成按钮:textFieldDidEndEditing:或textFieldShouldBeginEditing:或?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆