UITextfield文本颜色在不在焦点时不会改变 [英] UITextfield text color is not changing while not in focus

查看:87
本文介绍了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

这篇关于UITextfield文本颜色在不在焦点时不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆