UITextField 背景颜色更改。键入“blue”将背景设置为蓝色等

时间:2021-05-31 16:27:51

标签: swift xcode uitextfield background-color

我想将 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
}

1 个答案:

答案 0 :(得分:0)

您可以为 UITextField 添加一个扩展,以将 changeColor 函数添加到类中(在代码的任何部分,它必须在类之外)。然后制作一个fmt.Println(strconv.Itoa((0x00000800 >> 11) & 0x1F)) //working correctly //but my value comes as string src:= "0x00000800" fmt.Println(strconv.Itoa((src >> 11) & 0x1F)) //not working properly 函数来运行变色函数。最后,在 objc 中使用 objc 模式将 .editingChanged 函数定位到 textField。

ViewController 应如下所示:

viewDidLoad()