Swift UITextField没有连续的空格

时间:2017-05-15 10:50:02

标签: ios regex swift

如何禁止用户在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个字符。这是另一个要求。

6 个答案:

答案 0 :(得分:2)

您可以将文本字段中当前显示的文本与正在添加的新文本组合在一起。然后,您可以检查" "的出现情况。如果检测到此字符串,则返回false

答案 1 :(得分:2)

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

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

}

答案 2 :(得分:1)

Swift 3,Xcode 8.2

阻止用户输入空格键

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

    //Restrict
    if string == " " && textField.text?.characters.last == " "{
        return false
    }else{
        return true
    }
}

答案 3 :(得分:1)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let maxLegnth = 40
    let currentString: NSString = textField.text! as NSString
    let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString

    if textField.text?.characters.last == " " && string == " " {
        return false
    } else {
        return newString.length <= maxLegnth
    }
}

答案 4 :(得分:-1)

如何用“”(一个空格)替换“”(两个空格)。

答案 5 :(得分:-1)

试试这个正则表达式

var pattern=/(\s+){2,}/

 if(pattern.test(stringToCheck))
     {
    // string contain more than one consecutive space 
     }