Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

swift - Can't programmatically change color set in storyboard as color from xcassets catalog

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

enter image description here

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

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

... 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()
}

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")
}

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")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...