如何通过编程设置约束,使两个uiview的大小与屏幕大小无关?
我知道该如何在情节提要上进行约束,但我正在尝试学习以编程方式进行约束。
下面是我的情节提要约束的示例
这是我尝试使用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
答案 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)