【问题标题】:UITextField background color change. Typing "blue" set the background to blue etcUITextField 背景颜色改变。键入“蓝色”将背景设置为蓝色等
【发布时间】: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


【解决方案1】:

您可以为 UITextField 添加一个扩展,以将 changeColor 函数添加到类(在代码的任何部分,它必须在类之外)。然后做一个objc函数来运行变色功能。最后,将objc 函数定位到viewDidLoad().editingChanged 模式的textField。

ViewController 应该如下所示:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myTextField: UITextField!

    //Target function
    @objc func changeColor(_ sender:UITextField){
        sender.changeColor()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //Add target
        myTextField.addTarget(self, action: #selector(changeColor(_:)), for:      .editingChanged)
    }
}

//Extension to add function
extension UITextField{
    func changeColor() {
        if self.text == "blue" {
            self.backgroundColor = .blue
        } else if self.text == "red" {
            self.backgroundColor = .red
        } else {
            self.backgroundColor = .black
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    相关资源
    最近更新 更多