Search code examples
swiftxcodeanimationuilabeluicolor

Swift 4 UILabel animate Color


I'm trying to solve a problem for days, I hope you are able to help me.

In the app that i'm programming i am using a UITextField. In that TextField I want the user to type the word that is seen on the UILabel.
If he types the correct character I want the character on the label turning green, if its wrong then the label should turn red.

Can anyone help me or give me an advice?


Solution

  • You will get the text in textField delegate and depending upon your condition call the function updateLabel()

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        self.updateLabel(true, text: string)
        return true
    }
    
    
    
    func updateLabel(isCorrect:Bool, text: String){
    
        let textColor = isCorrect ? greenColor : redColor
          let attributedStringColor = [NSAttributedStringKey.foregroundColor : textColor];
    
          let attributedString = NSAttributedString(string: text, attributes: attributedStringColor)
          label.attributedText = attributedString
    }