Swift 4 UILabel 动画颜色

Swift 4 UILabel animate Color

几天来我一直在努力解决一个问题,希望你能帮助我。

在我正在编写的应用程序中,我使用的是 UITextField。 在该 TextField 中,我希望用户键入在 UILabel 上看到的单词。
如果他输入正确的字符,我希望标签上的字符变成绿色,如果输入错误,那么标签应该变成红色。

任何人都可以帮助我或给我建议吗?

您将在 textField 委托 中获得文本,并根据您的条件调用函数 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
}

实施UITextfieldDelegate

然后试试这个代码:

 func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {
   let enteredText = textField.text!

  if enteredText == yourLabel.text {
        yourLabel.textColor = UIColor.green

   }else{
        yourLabel.textColor = UIColor.red
       }

    return true
}