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

By simon at 2018-02-07 • 0人收藏 • 41人看过

我想改变视图的背景颜色,而文本字段有 特殊字符如123!@%^&()等otherwise背景颜色 应该是相同的颜色。 我已经实施,但根据每个角色不应该改变 是这样如果在整个文本字段中有任何特殊的字符就意味着颜色必须 更改。这是我的代码。

 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 个回复 | 最后更新于 2018-02-07
2018-02-07   #1

请在下面找到工作解决方案* 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

                }

登录后方可回帖

Loading...