设置ViewController的约束

时间:2018-10-24 07:21:22

标签: ios swift uiviewcontroller autolayout constraints

我正在将ViewController推到当前的ViewController上。

我要推送的ViewController是一个WebView,但我想那没关系。

Screenshot of the pushed ViewController

我希望显示的ViewController不要进入状态栏。但是如何设置这些约束?

这是我的代码,用于加载推送的ViewController:

@objc func loadWebView(sender: UIButton) {

        let vc = WebViewVC()

        webViewVC = vc

        self.present(webViewVC!, animated: true, completion: nil)

    }

如果我相对于父级ViewController的视图设置了webViewVC.view的约束,那么它当然会告诉我不允许这样做,因为视图位于不同的视图层次结构中。

这是我在WebViewVC中设置布局的方式:

func setUpView() {
        let view = UIView()
        self.view = view
        view.st(navigationBar,webView)

        navigationBar.heightAnchor.constraint(equalTo: webView.heightAnchor, multiplier: 0.1).isActive = true
        navigationBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
        navigationBar.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
        navigationBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
        navigationBar.bottomAnchor.constraint(equalTo: webView.topAnchor, constant: 0).isActive = true


        webView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
        webView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
        webView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: 0).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
    }

2 个答案:

答案 0 :(得分:2)

根据Apple文档:

  

布局指南,表示视图中没有被条形图和其他内容遮挡的部分。

使用以下方法更改导航栏的顶部锚点:

if #available(iOS 11, *) {
     let guide = view.safeAreaLayoutGuide
     navigationBar.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true

} else {
     navigationBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true 
}

答案 1 :(得分:1)

webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true

视图是您的 self.view ,而不是创建的新视图(view = UIView())