UITextfield文本颜色在不在焦点时不会改变

所以我有两个UITextFields :名称和金额以及两个UIButtons :收入,费用。
当我按下费用按钮时,如果按下收入按钮,我希望我的amount文本字段颜色变为红色或绿色。

仅当amount文本字段处于焦点时才有效,如果name文本字段处于焦点,则颜色不会更改为金额。

有没有办法改变文本字段的颜色,如果它不在焦点?

编辑:

这是我改变颜色的代码:

 @IBAction func typeBtnPressed(_ sender: UIButton) { if sender.tag == Buttons.expense.rawValue { amountTxt.textColor = .red } else { amountTxt.textColor = .green } } 

似乎iOS默认使用了originText而不是文本,这就是为什么没有发生任何事情,并且焦点似乎需要考虑你的textColor ,只是做

 let color: UIColor if sender.tag == Buttons.expense.rawValue { color = .red } else { color = .green } let attributedText = NSMutableAttributedString(attributedString: amountTxt.attributedText!) attributedText.setAttributes([NSAttributedStringKey.foregroundColor : color], range: NSMakeRange(0, attributedText.length)) amountTxt.attributedText = attributedText 

按下按钮后,这将立即生效

设置textColor后,需要将值重新分配给textField。

 textField.color = newColor textField.text = text