0

I want to change the background color of the view, while the text field has the Special characters like 123!@%^&() etc otherwise background colors should be the same color.

I have implemented but changing according to the each character it should not be like this if in entire text field any special character means color has to change. Here is my code.

 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
   }
K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43

1 Answers1

0

Please find below working solutions 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

                }