【问题标题】:Swift 4 UILabel animate ColorSwift 4 UILabel 动画颜色
【发布时间】:2018-07-23 11:11:33
【问题描述】:

我试图解决一个问题好几天了,希望你能帮助我。

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

谁能帮助我或给我建议?

【问题讨论】:

标签: swift xcode animation uilabel uicolor


【解决方案1】:

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

【讨论】:

  • 检查范围....使该范围内的字符变为绿色...不确定大小写错误.....整个标签变为红色或根据问题...
【解决方案2】:

实现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
}

【讨论】:

  • 他想改变单个字符的颜色,而不是整个标签的颜色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多