字符验证文本字段中的特殊字符

时间:2018-02-05 16:31:44

标签: swift3 swift4

我想更改视图的背景颜色,而文本字段包含123!@%^&()等特殊字符,否则背景颜色应该是相同的颜色。

我已经实现但是根据每个字符改变它不应该是这样的,如果在整个文本字段中任何特殊字符意味着颜色必须改变。 这是我的代码。

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

        let specialCharacters = "!~`@#$%^&*-+();:={}[],.<>?\\/\"\'"
        let searchText = textField.text! + string
        //

        let character = CharacterSet(charactersIn: specialCharacters)
        if (string.rangeOfCharacter(from: character) != nil){
            print("matched")
 self.view.backgroundColor = UIColor.gray
   }else
   {
    self.view.backgroundColor = UIColor.white
   }

1 个答案:

答案 0 :(得分:0)

请在下面找到工作解决方案 Swift 4

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                        let specialCharacters = "!~`@#$%^&*-+();:={}[],.<>?\\/\"\'"
                        var searchText = textField.text! + string
                      
                        let characterSet = CharacterSet(charactersIn: specialCharacters)
                        
                        if string == "" {
                                    searchText.removeLast()
                            }
                        
                        if (string.rangeOfCharacter(from: characterSet) != nil) {
                                    print("matched")
                                    self.view.backgroundColor = UIColor.gray
                                    textField.textColor = UIColor.white
                                    return true
                            } else  if (searchText.rangeOfCharacter(from: characterSet) == nil  ) {
                                    self.view.backgroundColor = UIColor.white
                                    textField.textColor = UIColor.black
                                    return true
                            }
                        return true

                }