首页 > 解决方案 > 无法设置 UILabel 的 textColor

问题描述

我目前正在研究源自 UITableViewCells Xibs 的动态表单。

if disabled {
    self.passTitleLabel.textColor = UIColor(named: "Dark Blue")
    self.textField.textColor = UIColor(named: "Dark Blue")
} else {
    self.passTitleLabel.textColor = UIColor(named: "Light Blue")
    self.textField.textColor = .white
}

UILabel ( passTitleLabel) 保留 Storyboard 文件中设置的颜色,并且不会按预期更改。UILabel 已启用且未突出显示,但仍保留情节提要上的颜色。

所有颜色都在其他类中工作(它们在Assets.xcassets)。使用 IBOutlet 正确设置标签。

标签: iosswiftuilabeluicolor

解决方案


遇到同样的问题,花了我一段时间,但终于找到了答案。看起来您的 UITableViewCell 或 UICollectionViewCell 正在后台线程中运行,UI 相关操作需要在主线程中完成,否则会导致此类问题。

if disabled {
   DispatchQueue.main.async {
      self.passTitleLabel.textColor = UIColor(named: "Dark Blue")
      self.textField.textColor = UIColor(named: "Dark Blue")
   }
} else {
   DispatchQueue.main.async {
      self.passTitleLabel.textColor = UIColor(named: "Light Blue")
      self.textField.textColor = .white
   }
}

推荐阅读