Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView's color cannot be changed programmatically after setting named color

Even when you create a fresh single view project (Xcode 9.2), create a single named color in an asset catalog, set the background color of the main view controller to this color in IB, and try to update the background color in viewDidLoad, the background color won't change. Have other people experienced this? Is this normal behavior?

view.backgroundColor = .red // Doesn't work, the asset color set in IB remains
like image 550
Joris Weimar Avatar asked May 16 '18 14:05

Joris Weimar


1 Answers

Super interesting and you are correct it does not change the color value as expected. There must be some delay as to when IB attributes are set in the super class. Wrapping the color change in DispatchQueue.main.async makes it work in viewDidLoad. Probably because this code would be processed last after whatever the super class is doing with IB attributes. Hope this solves the issue.

DispatchQueue.main.async {
   self.view.backgroundColor = UIColor.blue
}

Also in viewDidLayoutSubviews and viewDidAppear it works without the DispatchQueue but has the same behavior as viewDidLoad in viewWillAppear of not working as expected.

like image 78
agibson007 Avatar answered Sep 21 '22 02:09

agibson007