gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:52:21 25 4
gpt4 key购买 nike

如何通过编程设置约束使两个 uiview 大小相同而不管屏幕大小?

我知道如何对 Storyboard 进行约束,但我正在尝试学习以编程方式进行。

下面是我的 Storyboard约束的一个例子

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

最佳答案

您的代码应该可以正常工作,但您需要将其放入 viewDidLoad 中,并将每个 View 的 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)

关于ios - 如何以编程方式在父容器中制作两个相同大小的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52485888/

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