gpt4 book ai didi

ios - 使用自动布局约束以编程方式创建四个具有相同高度和宽度的 UIView

转载 作者:搜寻专家 更新时间:2023-11-01 05:51:29 25 4
gpt4 key购买 nike

如何以编程方式使用自动布局约束创建与下面相同的 View 。我一直在网上寻找资源,但我找不到任何在线教程来以编程方式创建 equalWidth 和 equalHeight 约束。

请告知如何以编程方式设置 equalWidth 和 equalHeight 以实现如下布局。

enter image description here

最佳答案

像这样:

/*
* ┌─┬─┐
* │1│2│
* ├─┼─┤
* │3│4│
* └─┴─┘
*/
override func viewDidLoad() {
super.viewDidLoad()
let view1 = UIView(frame: CGRectZero)
let view2 = UIView(frame: CGRectZero)
let view3 = UIView(frame: CGRectZero)
let view4 = UIView(frame: CGRectZero)

view1.backgroundColor = UIColor.yellowColor()
view2.backgroundColor = UIColor.redColor()
view3.backgroundColor = UIColor.greenColor()
view4.backgroundColor = UIColor.blueColor()

view1.setTranslatesAutoresizingMaskIntoConstraints(false)
view2.setTranslatesAutoresizingMaskIntoConstraints(false)
view3.setTranslatesAutoresizingMaskIntoConstraints(false)
view4.setTranslatesAutoresizingMaskIntoConstraints(false)

view.addSubview(view1)
view.addSubview(view2)
view.addSubview(view3)
view.addSubview(view4)

let views = ["view1":view1, "view2":view2, "view3":view3, "view4":view4]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view1][view2(==view1)]|", options: .allZeros, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view3][view4(==view3)]|", options: .allZeros, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view1][view3(==view1)]|", options: .allZeros, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view2][view4(==view2)]|", options: .allZeros, metrics: nil, views: views))


// Do any additional setup after loading the view, typically from a nib.
}

关于ios - 使用自动布局约束以编程方式创建四个具有相同高度和宽度的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26884949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com