Swift如何正确设置TextField的背景颜色和文字颜色

How to properly set TextField's background color and text color in Swift

请不要标记为重复,因为我似乎有一个错误,通常的代码不起作用。我遍历了所有可用的线程,但没有找到解决方案。

我有以下单元格:

UISwitch 关闭时,我希望 UITextField 变暗,文字颜色变亮。开启时相反模拟一个"disable"行为。

我的代码:

func setTextFieldActivation(isOn: Bool) {

    self.theTextField.isUserInteractionEnabled = isOn

    self.theTextField.set(

        bgColor: isOn ? Colors.moreLightGrey : Colors.leastLightGray, //Colors is a global struct of UIColor to cache reused colors
        placeholderTxt: String(),
        placeholderColor: isOn ? Colors.black : Colors.white,
        txtColor: isOn ? Colors.black : Colors.white
    )
}

分机set

extension UITextField {


    func set(bgColor: UIColor, placeholderTxt: String, placeholderColor: UIColor, txtColor: UIColor) {

        self.backgroundColor = bgColor
        self.attributedPlaceholder = NSAttributedString(string: placeholderTxt, attributes: [NSForegroundColorAttributeName: placeholderColor])
        self.textColor = txtColor
    }
}

问题:当我打开 UISwitch 时,背景颜色会根据需要更改,但文本颜色仍然存在。

奇怪的部分:当我点击 UITextField 并且它成为第一响应者时,文本颜色变为我想要的颜色。

但是当我再次关闭 Switch 时,颜色仍然很暗。

我错过了什么?非常感谢帮助。

PS: Xcode 9, Swift 3.

每当开关改变时调用代码:

self.theSwitch.addTarget(self, action: #selector(switchChanged), for: .valueChanged)

func switchChanged(mySwitch: UISwitch) {

    self.setTextFieldActivation(isOn: mySwitch.isOn)
}

我想我明白了。有线的事情是 textColor 直到 layoutSubviews() 才更新。我尝试了两种似乎可以解决问题的方法。

第一种方法是在set方法的末尾直接调用layoutSubviews()

func set(bgColor: UIColor, placeholderTxt: String, placeholderColor: UIColor, txtColor: UIColor) {

    backgroundColor = bgColor
    attributedPlaceholder = NSAttributedString(string: placeholderTxt, attributes: [NSForegroundColorAttributeName: placeholderColor])
    textColor = txtColor

    layoutSubviews()
}

第二种方法是将 UITextField 的文本设置为其当前值,这也会触发 layoutSubviews()

func set(bgColor: UIColor, placeholderTxt: String, placeholderColor: UIColor, txtColor: UIColor) {

    backgroundColor = bgColor
    attributedPlaceholder = NSAttributedString(string: placeholderTxt, attributes: [NSForegroundColorAttributeName: placeholderColor])
    textColor = txtColor

    let newText = text
    text = newText
}