通过评估TextField的文本来更改文本颜色

时间:2019-04-22 14:59:20

标签: swift

我想根据验证将文本颜色更新为绿色。但是,“ shouldChangeCharactersInRange”文本在返回true之前不可用。

每次只有一个字符串被设置为绿色。

要求:我想存储所有通过的条件,并将它们的颜色更改为绿色,然后在textView中进行设置。如果条件失败,则特定内容应为红色。

UITextFieldDelegate Method: 

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//My Method that validates
    validate(text: textField.text!)
    return true
}


textViewStringArray = [ "• A minimum of 8 characters",
"• At least 1 number",
"• At least 1 Upper case letter",
"• At least 1 Lower case letter",
"• At least 1 of the  following special characters: !,@,#,$,*"]

 func validate(text: String) {

    let smallLetterRegEx  = "[a-z]"
    let capitalLetterRegEx  = "[A-Z]"
    let smallLetterText = NSPredicate(format:"SELF MATCHES %@", smallLetterRegEx)
     if smallLetterText.evaluate(with: password) {

        let str = textViewStringArray.joined(separator: "\n")
        let lowerCaseString = "• At least 1 Lower case letter"
        let range = (str as NSString).range(of: lowerCaseString)
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.darkGreen, range: range)
        DispatchQueue.main.async {
            self.textView.attributedText = attribute
        }

        self.view.setNeedsDisplay()
        //label.attributedText = str
    }


    let capitalLetter = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx)
    if capitalLetter.evaluate(with: password) {
        let str = textViewStringArray.joined(separator: "\n")
        let lowerCaseString = "• At least 1 Upper case letter"
        let range = (str as NSString).range(of: lowerCaseString)

        DispatchQueue.main.async {
            let attribute = NSMutableAttributedString.init(string: str)
            attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.darkGreen, range: range)
            self.textView.attributedText = attribute
        }



    }

1 个答案:

答案 0 :(得分:0)

尝试使用notebook_url来检查字符串格式是否等于模型的格式,而不是在“ shouldchangecharacter”中进行比较 使你的模型像这样 如果string.count> 8 && string。包含等等