【问题标题】:How to change label color when you change label text更改标签文本时如何更改标签颜色
【发布时间】:2018-01-26 10:04:17
【问题描述】:

我是新来的... 我有一个文本字段和一个标签...我想更改标签颜色,以防文本字段中的消息和标签文本不相等。 这是我的开始:

@IBAction func tapMeButton(_ sender: Any) {

    label.text = txtField.text

    }

我该怎么做?

【问题讨论】:

  • UILabels 有一个textColor 字段,它接受一个UIColor。您可以使用if 语句来确定消息是否相同(如果您不关心大小写,您可能希望将两个字符串都设置为小写)。

标签: ios swift xcode


【解决方案1】:

将此行添加到 viewDidLoad

  textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

@objc func textFieldDidChange(_ textField: UITextField) {

   if(label.text != txtField.text)
  {
      label.textColor = UIColor.red
  }

}

@IBAction func tapMeButton(_ sender: Any) {

    label.text = txtField.text
}

【讨论】:

  • 感谢您的回答。但是我想在更改文本时更改颜色。一开始,当我按下按钮时,我的文本字段和我的标签是相同的。然后,当我想在文本字段中写入新文本时更改标签颜色时。
【解决方案2】:

UITextField 提供委托方法,您可以使用此代码检查两个 Value 是否相同。

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let nsString = textField.text as NSString?
        let newString = nsString?.replacingCharacters(in: range, with: string)

        if(self.lbl.text != newString) {
             self.lbl.textColor = UIColor.red
        }
        else {
             self.lbl.textColor = UIColor.green
        }

        return true;
     }

【讨论】:

    【解决方案3】:

    首先添加获取文本变化的目标。

    textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    
    func textFieldDidChange(_ textField: UITextField) {
        if(label.text != textField.text)
     {
       label.textColor = UIColor.red
     }
    }
    

    你也可以看到这个:https://stackoverflow.com/a/28395000/5167909

    【讨论】:

      【解决方案4】:

      要做到这一点,你必须更多地了解文本字段,

      1. 每个文本字段都带有委托方法来围绕它执行各种功能。 所以首先在你的 viewDidLoad 方法中,像这样向它添加委托

        yourTextField.delegate = self
        
      2. 通过添加扩展将 textFieldDelegate 分配给您的类来添加委托方法。它会在用户开始输入甚至被添加到 textField 之前实时为您提供文本

        extension YourViewController:UITextFieldDelegate {
        
        
            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        
            if let text = textField.text as NSString? {
                let txtAfterUpdate = text.replacingCharacters(in: range, with: string)
        
                if txtAfterUpdate == label.text {
        
                    label.backgroundColor = UIColor.red
        
                } else {
        
                    label.backgroundColor = UIColor.black
                    }
        
        
                }
                return true
        
            }
        
        
        
        }
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        • 1970-01-01
        • 2022-08-08
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        相关资源
        最近更新 更多