如何禁止用户在UITextField中键入两个连续的空格?

我尝试使用的代码如下:

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

    let myString = myUITextField.text

    let regex = try? NSRegularExpression(pattern: " +", options: .caseInsensitive)
    let trimmedString: String? = regex?.stringByReplacingMatches(in: myString!, options: [], range: NSRange(location: 0, length: (myString?.characters.count)!), withTemplate: " ")

    myUITextField.text = trimmedString

    let maxLegnth = 40
    let currentString: NSString = textField.text! as NSString
    let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString

    return newString.length <= maxLegnth
}

PS:其余代码强制用户仅输入40个字符。这是另一个要求。

最佳答案

只需检查用户输入的上一个和当前字符。

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

if textField.text?.characters.last == " "  && string == " "{

// If consecutive spaces entered by user
 return false
}

// If no consecutive space entered by user

return true

}

10-08 05:48
查看更多