以编程方式将表添加到导航控制器视图不起作用

时间:2017-10-18 09:07:29

标签: ios uinavigationcontroller autolayout nslayoutconstraint

尝试添加表格以覆盖视图控制器的整个视图时,如下所示:

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;
}

表格不显示。我是否正确假设topAnchor在导航控制器的上下文中我们指的是视图控制器视图的顶部(导航栏结束的位置?)。这看起来很简单,所以我明显遗漏了一些明显的东西。谢谢。

1 个答案:

答案 0 :(得分:1)

每当您在代码中创建视图并尝试向该视图添加约束时,您必须记住设置 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;
}