如何在完成编辑时检查UITextField文本是否为空



我目前有一个带有默认文本的UITextField,并设置为在编辑开始时清除。 我正在尝试这样做,以便在编辑完成时字段为空或为零,则文本值将再次成为默认文本。 我在检测何时完成编辑或关闭键盘时遇到问题。 谁能告诉我我想使用哪种检测方法以及如何实现它? 非常感谢!

<小时 />

编辑

<小时 />

placeholder不能用于我的情况

你必须

使用文本字段委托

-(void)textFieldDidEndEditing:(UITextField *)textField;

在此代表中,像这样进行检查

if ( [textField.text length] == 0 )
{
    // the text field is empty do your work
} else {
    ///  the text field is not empty 
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
    if (range.location == 0 && string.length == 0)
    {
        //textField is empty
    }
    return YES;
}

我认为您不需要自己处理"默认文本"。检查UITextFieldplaceholder属性。

更新

所以placeholder对你的案子不利。您是否尝试为UITextField实现UITextFieldDelegate方法并更改textViewDidEndEditing:中的文本?

为此,请在视图控制器中实现UITextFieldDelegate这些方法看起来对你的方案有用,并将delegate UITextField设置为视图控制器(通过界面生成器或以编程方式)。在textViewDidEndEditing:方法中设置默认文本。

您可以参考 iOS 版文本、Web 和编辑编程指南的"获取输入的文本和设置文本"部分。

当您收到文本字段返回时的委托调用时,请使用 sender 参数检查文本 ( sender.text ),如果等于 @""设置默认文本。

我使用2种方法。我的选择取决于应用程序业务逻辑。

1)我在应用shouldChangeCharactersIn更改后检查结果文本:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var text = textField.text ?? ""
        let startIndex = text.index(text.startIndex, offsetBy: range.location)
        let endIndex = text.index(text.startIndex, offsetBy: range.location + range.length)
        text = text.replacingCharacters(in: startIndex..<endIndex, with: string)
        if text.count == 0 {
            // textField is empty
        } else {
            // textField is not empty
        }
        return true
    }

2)我使用editingChanged动作:

@IBAction private func textFieldDidChange(_ sender: UITextField) {
        if (sender.text?.count ?? 0) == 0 {
            // textField is empty
        } else {
            // textField is not empty
        }
    }

您还需要检查删除的范围是否是文本的整个长度。

func textField(_ textField: UITextField, shouldChangeCharactersIn range:  NSRange, replacementString string: String) -> Bool {
    if !(range.location == 0 && string.count == 0 && range.length == textField.text?.count) {
      // Text field is empty
    }
    return true
}