我已经创建了一个xib并在我的viewDidLayOutSubviews
中加载了nib:
然后我添加了子视图:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if (myCustomView == nil) {
myCustomView = Bundle.main.loadNibNamed("Help", owner: self, options: nil)?.first as? HelpView
self.view.addSubview(myCustomView!)
}
}
我的约束都在我的xib中正确设置(在设备之间切换看起来没问题),但是当我在其他设备上启动应用程序时,自动布局不会更新。我该如何解决?谢谢!
编辑:
答案 0 :(得分:1)
您的约束可能在您的笔尖中正确设置,但是当您调用self.view.addSubview(myCustomView!)时,您没有任何约束,因此框架将成为笔尖中的任何内容文件。您需要将myCustomView约束为self.view。给它等宽,中心X,等于顶部和固定高度(或使用固有高度),它应该没问题。确保关闭translatesAutoresizingMaskIntoConstraints。
答案 1 :(得分:0)
只需在
下面添加此行<强> self.view.addSubview(myCustomView!)强>
myCustomView.translatesAutoresizingMaskIntoConstraints = false;
//Views to add constraints to
let views = Dictionary(dictionaryLiteral: ("myCustomView",myCustomView))
//Horizontal constraints
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[myCustomView]|", options: nil, metrics: nil, views: views)
self.view.addConstraints(horizontalConstraints)
//Vertical constraints
let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[myCustomView(SpecifyFixedHeight)]|", options: nil, metrics: nil, views: views)
self.view.addConstraints(verticalConstraints)