swift - 无法以编程方式将 Storyboard 中的颜色集更改为 xcassets 目录中的颜色

标签 swift xcode colors uicolor xcasset

当我将 Storyboard 中某些属性的颜色(例如 UILabeltextColor)设置为在 xcassets 目录中创建为新颜色集的颜色时

enter image description here

然后我无法在第一次尝试时以编程方式更改此颜色:

label.textColor = UIColor(named: "HighlightedGreen")

...请注意,我是从数据源方法 cellForItemAt 中调用它的。

破解: 我可以通过在 Storyboard 中为从颜色选择器中选择的任何其他颜色设置这种颜色来解决这个问题,但我想知道为什么会这样。

那么,为什么会这样呢?

最佳答案

UIView subClassUITableViewCellStoryboard/Xib 加载时,它应用指定的属性在 Attribute Inspector 中添加到所有 subViews。我们有以下回调方法来了解何时从 Storyboard/Xib 加载 View ,

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()        
}

override func awakeFromNib() {
    super.awakeFromNib()
}

这些方法可能是添加/删除 subview 的良好候选者,但它们不应该更新 subview 的 size 或一些 attribute inspector 相关属性。更新 subview 的推荐方法是当 super View 完成加载并应用所有 attribute inspector 属性并调用 layoutSubviews 时。因此,您应该对 subview 应用任何外观更改。例如,

override func layoutSubviews() {
    super.layoutSubviews()

    label.textColor = UIColor(named: "HighlightedGreen")
}

对于 UITableViewCell,任何实现 UITableViewDataSource 的对象还保证 delegate 方法在单元格显示之前应用任何修饰更改,如下所示, 所以这也是另一个改变颜色的好候选。

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    (cell as! MyListTableViewCell).label.textColor = UIColor(named: "HighlightedGreen")
}

关于swift - 无法以编程方式将 Storyboard 中的颜色集更改为 xcassets 目录中的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53583593/

相关文章:

android - 在图像的每个像素和二进制值中生成带有颜色的 QR 码

css - 鼠标悬停拾色器时更改产品颜色

swift - 从任何 ViewController 访问类变量

ios - Xcode XCTestCase 根本没有运行

ios - Xcode 构建错误链接器命令失败,退出代码为 1

ios - iPhone 拒绝了发布请求。内部启动错误: process launch failed: Unspecified

Swift @autoclosure 参数包装提供显式关闭

ios - 如何以编程方式更改 UIButton 属性文本颜色?

ios - 如何在用户注销后正确释放 ViewControllers?

Android 内边距颜色