限制在 TextField 中输入的字符串数量 - Swift

Limitate number of string to type in TextField - Swift

我想限制我的用户在我的 TextField 中只输入 3 个词。我发现了其他一些正在谈论限制输入中的 char 的主题,但这不是我想要的。

有人知道是否可以计算 TextField 中的 space 并在输入超过 3 个 space 时做一种 if 语句 你不能写还要别的吗?

Ex: "Boys rescued in Thailand" should be blocked after "Boys rescued in"

提前致谢!

我相信你可以使用自定义验证函数,该函数将从字段中获取字符串,然后将其拆分为数组。并检查数组的长度。

var fullName = "First Last"
var fullNameArr = split(fullName) {[=10=] == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

最快的解决方案是挂接到 textField 的委托方法 shouldChangeCharactersIn

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if let text = textField.text, text.split(separator: " ").count < 3 {
        return true
    }
    return (string == "" || string != " ")
}

在 TextField 委托方法中

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

像这样检查一下

var wordCount = 0
if let text = textField.text {
    wordCount = text.split(separator: " ").count
}
if wordCount < 3 {
    return true
}
return false