所以我有两个UITextFields:名字和金额和两个UIButtons:收入,费用.
当我按下费用按钮时,amount如果按下收入按钮,我希望我的文本字段颜色变为红色或绿色.
仅当amount文本字段处于焦点时才有效,如果name文本字段处于焦点,则颜色不会更改为金额.
有没有办法改变文本字段的颜色,如果它不在焦点?
编辑:
这是我改变颜色的代码:
@IBAction func typeBtnPressed(_ sender: UIButton) {
if sender.tag == Buttons.expense.rawValue {
amountTxt.textColor = .red
} else {
amountTxt.textColor = .green
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
设置textColor后,需要将值重新分配给textField.
textField.color = newColor
textField.text = text
Run Code Online (Sandbox Code Playgroud)
似乎iOS默认使用attributedText而不是文本,这就是为什么什么都没有发生的原因,并且在焦点上它似乎考虑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
Run Code Online (Sandbox Code Playgroud)
这将在按下按钮后立即工作
Swift 4 Xcode 10 版
let attributedText = NSMutableAttributedString(attributedString: textField.attributedText!)
attributedText.setAttributes([NSAttributedString.Key.foregroundColor : UIColor.red], range: NSMakeRange(0, attributedText.length))
textField.attributedText = attributedText
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3194 次 |
| 最近记录: |