使用可视格式约束时,子视图未显示在scrollview中

时间:2016-10-20 18:29:14

标签: ios swift

我无法理解为什么蓝色视图没有显示请看看我的代码。当我在主视图中使用view.addSubView(mapView)其节目时,但当我scrollView.addSubView(mapView)时,它不会显示。但是约束条件似乎都是正确的。我不确定为什么它不起作用。

import UIKit



class practiceViewController: UIViewController,UIScrollViewDelegate {
    override func viewDidLoad() {
        var allConstraint = [NSLayoutConstraint]()

        let scrollView:UIScrollView = {
            let v = UIScrollView()
            v.backgroundColor = .red
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()

        let mapView:UIView = {
            let v = UIView()
            v.backgroundColor = .blue
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()

        //views
        let views = [
            "scrollView":scrollView,
            "mapView":mapView
        ]
        //add views
        view.addSubview(scrollView)
        scrollView.addSubview(mapView)

       // constraints
        let scrollviewHorizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)
        let scrollviewVerticleConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: views)

        allConstraint += scrollviewVerticleConstraint
        allConstraint += scrollviewHorizontalConstraint

        let mapViewHorizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|[mapView]|", options: [], metrics: nil, views: views)
        let mapViewVerticleConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|[mapView]|", options: [], metrics: nil, views: views)

        allConstraint += mapViewHorizontalConstraint
        allConstraint += mapViewVerticleConstraint

        NSLayoutConstraint.activate(allConstraint)
    }

}

1 个答案:

答案 0 :(得分:0)

您的mapView需要宽度和高度。滚动视图在您设置内容大小之前不知道内容大小是什么,因此scrollview默认为零。尝试这样的事情:

let mapViewHorizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|[mapView(200)]|", options: [], metrics: nil, views: views)
let mapViewVerticleConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|[mapView(200)]|", options: [], metrics: nil, views: views)