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

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

问题描述:

所以我有两个 UITextFields :名称和金额以及两个 UIButtons :收入,费用。

当我按下费用按钮时,如果按下收入按钮,我希望我的金额文本字段颜色变为红色或绿色。

So I have two UITextFields: name and amount and two UIButtons: income, expense.
When I press the expense button I want my amount textfield color to change to red or green if income button is pressed.

仅当金额 textfield成为焦点时才有效,如果 name textfield是焦点,颜色不会更改金额。

This only works if amount textfield is in focus, if name textfield is in focus, the color is not changed for amount.

如果文本域没有聚焦,有没有办法改变文本字段的颜色?

Is there a way to change the color of the textfield if it's not in focus ?

编辑:

这是我更改颜色的代码:

Here is my code where I change the color:

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


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

It seems iOS uses by default attributedText and not text, that is why nothing is happening, and on focus it seems it takes your textColor into account, just do

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

一旦按下按钮,这将立即生效

This will then work as soon as button is pressed