Tom Fox Tom Fox - 1 month ago 14
Swift Question

Buttons obstructed due to UIView created due to custom table view style code (Xcode8)

I use the following code to change the background colour and border radius of a UITableView:

let containerView:UIView = UIView(frame:self.gamesTableView.frame)
gamesTableView.layer.cornerRadius = 5
gamesTableView.layer.masksToBounds = true
gamesTableView.backgroundColor = UIColor(red:1, green:1, blue:1, alpha:0.40)
self.view.addSubview(containerView)
containerView.addSubview(gamesTableView)


This worked fine in xcode 7 and produced the result I expected. However in Xcode 8 this code seems to cause the buttons on the screen not to work, using the debug view hierarchy tool I discovered that with this code there is an extra UIView created that seems to obstruct the buttons. Removing the code in question does solve the problem but it also takes away the extra traits I gave the table view. I would like to know whether there is an alternative method to achieve the same result. I have included images of the view hierarchy with and with out the code.

The buttons in question are: "Start new game" and "Settings"
gg

Side view without styling code:
enter image description here

Side view with sling code, notice the highlighted layer in front:
enter image description here

Answer

The fix for this seems to be as simple as putting the code in the question above in viewDidLayoutSubviews

Like this:

override func viewDidLayoutSubviews(){
    let containerView:UIView = UIView(frame:self.gamesTableView.frame)
    gamesTableView.layer.cornerRadius = 5
    gamesTableView.layer.masksToBounds = true
    gamesTableView.backgroundColor = UIColor(red:1, green:1, blue:1, alpha:0.40)
    self.view.addSubview(containerView)
    containerView.addSubview(gamesTableView)
}