【问题标题】:How to properly set TextField's background color and text color in Swift如何在 Swift 中正确设置 TextField 的背景颜色和文本颜色
【发布时间】:2017-10-27 16:26:46
【问题描述】:

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

我有以下单元格:

UISwitch 关闭时,我希望UITextField 变暗,文本颜色变亮。当打开相反时模拟“禁用”行为。

我的代码:

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 并成为第一响应者时,文本颜色会变为我想要的颜色。

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

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

PS:Xcode 9,Swift 3。

只要切换开关就会调用代码:

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

func switchChanged(mySwitch: UISwitch) {

    self.setTextFieldActivation(isOn: mySwitch.isOn)
}

【问题讨论】:

  • 您是否在其他地方更改文本颜色?我用您的代码构建了一个文本字段测试应用程序,它可以工作。我必须在 viewDidLoad() 中添加一个初始调用 set(bgColor:, placeholderTxt:, placeholderColor:, txtColor:)。
  • 不,我不会在其他任何地方更改它。每当更改开关时都会调用该代码。见编辑。
  • 也许调用代码的时间/地点有问题?我将 IBAction 用于 UISwitch 并调用 setTextFieldActivation(isOn: sender.isOn)。
  • 您是否在viewDidLoad 上调用setTextFieldActivation 方法?可能没有设置初始值,这会扰乱切换操作的行为。
  • 它在一个单元格中,一旦单元格在cellForRow中被调用,我就会调用它

标签: swift uitextfield uiswitch


【解决方案1】:

我想我明白了。连线的事情是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
}

【讨论】:

  • layoutSubviews() 做到了。谢谢你的努力
  • 如果我在collectionView里面做呢
猜你喜欢
  • 2016-10-04
  • 2013-07-29
  • 2017-09-04
  • 2019-09-09
  • 1970-01-01
  • 2011-09-12
  • 2021-11-17
  • 2017-06-08
  • 2011-02-14
相关资源
最近更新 更多