不允许空输入

Disallowing empty input

我们如何禁止在 textField 上输入空值?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let oldText = textField.text!
    let stringRange = Range(range, in:oldText)!
    let newText = oldText.replacingCharacters(in: stringRange, with: string)
    doneBarButton.isEnabled = !newText.isEmpty  
    return true
}

还有其他方法吗?或使用其他 textField 委托方法来执行此操作?

是的,基本上就是这样。

或者,如果您想知道该字段是否为空,只需计算结果的长度即可:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let length = (textField.text?.count ?? 0) + string.count - range.length
    doneBarButton.isEnabled = length > 0
    return true
}

您可能还想将文本字段的 enablesReturnKeyAutomatically 设置为 true,这样除非字段中有文本,否则键盘不会启用“return”键。