无法以编程方式将情节提要中设置的颜色更改为 xcassets 目录中的颜色 [英] Can't programmatically change color set in storyboard as color from xcassets catalog

查看:34
本文介绍了无法以编程方式将情节提要中设置的颜色更改为 xcassets 目录中的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I set color of some property in Storyboard (for example textColor of my UILabel) as color created as New Color Set in xcassets catalog

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

then I can't programmatically change this color on the first attempt:

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

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

... note that I'm calling it from data source method cellForItemAt.

黑客:我可以通过在 Storyboard 中为从颜色选择器选择的任何其他颜色设置此颜色来解决它,但我想知道为什么会发生这种情况.

Hack: I can solve it by setting this color in Storyboard for any other color picked from color picker but I want to know why is this happening.

那么,为什么会发生这种情况?

So, why is this happening?

推荐答案

UIView subClassUITableViewCell 被加载时>Storyboard/Xib,它将Attribute Inspector 中指定的属性应用于所有subViews.我们有以下回调方法来知道何时从 Storyboard/Xib 加载视图,

When a UIView subClass like UITableViewCell is loaded from the Storyboard/Xib, it applies the attributes specified in Attribute Inspector to all the subViews. We have the following callback methods to know when a view is loaded from the Storyboard/Xib,

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

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

这些方法可能是添加/删除子视图的不错选择,但它们不应该更新子视图的 size 或某些 attribute inspector 相关属性.更新子视图的推荐方法是当超级视图完成加载和应用所有 attribute inspector 属性并调用 layoutSubviews 时.因此,您应该将任何外观更改应用于子视图.例如,

These methods could be good candidates to add/remove a subView but they are not supposed to update the subView's size or some of attribute inspector related properties. The recommended method to update subViews is when the super view finishes loading and applying all the attribute inspector properties and calls layoutSubviews. So then you should apply any cosmetic change to a subView. e.g,

override func layoutSubviews() {
    super.layoutSubviews()

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

对于 UITableViewCell,任何实现 UITableViewDataSource 的对象也保证 delegate 方法在显示单元格之前应用任何外观更改,如下所示, 所以这也是换颜色的另一个好人选.

For a UITableViewCell, any object implementing UITableViewDataSource also guarantees a delegate method to apply any cosmetic change before the cell is being displayed as below, So this is also another good candidate to change the color.

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

这篇关于无法以编程方式将情节提要中设置的颜色更改为 xcassets 目录中的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆