Search code examples
iosuinavigationcontrollerautolayoutnslayoutconstraint

Adding table to navigation controller view programatically doesnt work


When attempting to add a table to cover the entire view of a view controller like so:

func setConstraints(){

    self.view.addSubview(statisticsTable);

    statisticsTable.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true;
    statisticsTable.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true;
    statisticsTable.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true;
    statisticsTable.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true;
}

The table doesnt display. Am i correct to assume that by topAnchor in the context of a navigation controller we mean the top part of the view contrller view ( which is where the navigatio bar ends? ). This looks quite simple so im clearly missing something obvious here. Thank you.


Solution

  • whenever your creating a view in code and tries to add constraints to that view you have to remember to set the translatesAutoresizingMaskIntoConstraints

    func setConstraints(){
    
        self.view.addSubview(statisticsTable);
        // try to add this before you add your constraints to the view
        statisticsTable.translatesAutoresizingMaskIntoConstraints = false
    
        statisticsTable.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true;
        statisticsTable.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true;
        statisticsTable.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true;
        statisticsTable.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true;
    }