【发布时间】:2021-08-18 23:23:05
【问题描述】:
我想将 myTextField 背景颜色更改为我在同一个 myTextField 中键入的颜色。这是我的方法: 我还在 viewDidLoad 部分调用了这个方法:changeColor() 但它不起作用:(
func changeColor() {
if myTextField.text == "blue" {
myTextField.backgroundColor = .blue
} else if myTextField.text == "red" {
myTextfield.backgroundColor = .red
} else {
myTextField.backgroundColor = .black
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == myTextField {
if range.location > 3 {
return false
}
}
return true
}
【问题讨论】:
-
发生了什么?
changeColor()仅在viewDidLoad()中调用?那么myTextField.text的值是多少?你不应该想听文字变化并在那里打电话给changeColor()吗?你看看怎么做吗?通过实现UITextFieldDelegate方法? -
UITextFieldDelegate 已实现,我可以输入任何内容,它出现在 textField 中。当应用程序启动时,文本字段为空,其背景颜色为白色(默认),当我输入“蓝色”或“红色”时没有任何反应,但我希望将背景颜色设置为蓝色或红色
-
@LászlóGábor 你实现
shouldChangeCharactersIn了吗? -
你没有在对应的
UITextFieldDelegate方法中调用changeColor()?一开始,它确实应该是黑色的,而不是白色的。你能显示更多代码吗? -
是的,当我设置最大字符数 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == myTextField { if range.位置 > 3 { 返回 false } } 返回 true }
标签: swift xcode uitextfield background-color