Search code examples
iosswiftuitableviewios9

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 UITableView, which is a subview of my custom view, in code and set the background color during my subview's init method.

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

or

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

Is there anything else that I can try?


Solution

  • 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() {
        super.layoutSubviews()
        self.backgroundColor = customColor
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        self.backgroundColor = customColor
    }
    

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

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