【问题标题】:Disallowing empty input禁止空输入
【发布时间】:2019-02-13 16:58:09
【问题描述】:

我们如何禁止 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 委托方法来做到这一点?

【问题讨论】:

    标签: ios swift input uitextfield textfield


    【解决方案1】:

    是的,基本上你就是这样做的。

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

    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,这样键盘就不会启用“返回”键,除非该字段中有文本。

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2016-07-14
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多