添加子视图时,Autolayout无法为我的笔尖工作

时间:2017-04-25 05:25:30

标签: ios swift uiview

我已经创建了一个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中正确设置(在设备之间切换看起来没问题),但是当我在其他设备上启动应用程序时,自动布局不会更新。我该如何解决?谢谢!

编辑:

为iPhone 7做好了准备,但推出了iPhone 7 Plus enter image description here

为iPhone 7 Plus启用iPhone 7 Plus enter image description here

2 个答案:

答案 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)
相关问题