如何以编程方式在父容器中制作两个相同大小的UIView

时间:2018-09-24 19:13:54

标签: ios swift autolayout

如何通过编程设置约束,使两个uiview的大小与屏幕大小无关?

我知道该如何在情节提要上进行约束,但我正在尝试学习以编程方式进行约束。

下面是我的情节提要约束的示例

enter image description here

这是我尝试使用viewwilllayoutsubview()

    view.addSubview(topView)
    view.addSubview(bottomView)

    topView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    topView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    topView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    topView.heightAnchor.constraint(equalToConstant: view.frame.size.height / 2).isActive = true

    bottomView.topAnchor.constraint(equalTo: topView.bottomAnchor).isActive = true
    bottomView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    bottomView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    bottomView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

1 个答案:

答案 0 :(得分:1)

您的代码应该可以正常工作,但您需要将其放入viewDidLoad内,并将每个视图的translatesAutoresizingMaskIntoConstraints设置为false

topView.translatesAutoresizingMaskIntoConstraints = false
bottomView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([

     topView.topAnchor.constraint(equalTo: view.topAnchor) ,
     topView.leadingAnchor.constraint(equalTo: view.leadingAnchor) ,
     topView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
     topView.heightAnchor.constraint(equalToConstant: view.frame.size.height / 2),

     bottomView.topAnchor.constraint(equalTo: topView.bottomAnchor),
     bottomView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
     bottomView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
     bottomView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])

您也可以替换

topView.heightAnchor.constraint(equalToConstant: view.frame.size.height / 2)

使用

topView.heightAnchor.constraint(equalTo: bottomView.heightAnchor)