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

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

问题描述

当我在情节提要中设置某些属性的颜色(例如我的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.

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

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?

推荐答案

当从Storyboard/Xib加载UIView subClass(如UITableViewCell)时,它将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()
}

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

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天全站免登陆