Suragch Suragch - 1 year ago 76
Swift Question

Programmatically created UITableView always white in iOS9

I can't get my UITableView to change colors on start up with iOS 9.

I created a

, which is a subview of my custom view, in code and set the background color during my subview's

myTableView.backgroundColor = UIColor.yellowColor()

But it stayed white.

I used View Debugging > Capture View Hierarchy to confirm that it is the table view itself and not the table view cells that are white. (But I set the cells to clear anyway just in case).

I've seen a lot of older posts that talk about a similar problem (like this, this and this and this newer one) so I tried things like

myTableView.backgroundView = nil // or UIView()


myTableView.backgroundView.backgroundColor = UIColor.clearColor()

but these also didn't work.

I discovered that if I did

myTableView.backgroundColor = UIColor.yellowColor()

sometime after the original layout (for example, on a button tap), then it would change the background color.

This is all only a problem in iOS 9.3. In my tests with iOS 8.1 and 8.4 I had no problems setting the background color during

Is there anything else that I can try?

Answer Source

init method is not a good place to modify UI properties because the view hierarchy hasn't been constructed yet.

Try using layoutSubviews or didMoveToWindow for UIView subclasses:

var customColor = UIColor.yellowColor()
override func layoutSubviews() {
    self.backgroundColor = customColor

override func didMoveToWindow() {
    self.backgroundColor = customColor

You can also use viewDidLoad or awakeFromNib methods in UIViewController subclasses:

override func viewDidLoad() {
    customTableView.backgroundColor = UIColor.yellowColor()

override func awakeFromNib() {
    customTableView.backgroundColor = UIColor.yellowColor()