How to add programmatic constraints to a UITableView?

Viewed 11496

I have a class set up as follows:

class SettingsController: UITableViewController {

I would like to be able to add constraints to the UITableView so that there is equal spacing either side of the table (it is currently a full width table, so a little ugly on iPad).

I have read that I can't add constraints to a UITableViewController, and instead I must add a UIViewController to my class, add a UITableView to that, and then I should be able to add the constraints to the TableView.

I've amended the class and defined the UITableView on the next line. So here are my first two lines now:

class SettingsController: UIViewController {
  var tableView = UITableView()

Further down, I have this code to attach the TableView to the UIView:

override func viewDidLoad() {
    super.viewDidLoad()   
    self.view.addSubview(tableView)
}

The app builds successfully but when trying to access this view, the screen is blank, so I've not been able to attempt the constraints part yet (the screen does display the data correctly if I revert what I've described).

Many of my existing functions within this class reference tableView for passing in the data/setting the number of rows etc, but it seems I've not done something right... is there a piece I'm missing?

3 Answers
Related