gpt4 book ai didi

swift - 如何在 UIView 中居中放置多个元素

转载 作者:行者123 更新时间:2023-11-28 08:31:15 26 4
gpt4 key购买 nike

我试图将多个元素(标签和按钮)置于 UIView(或 UIStackView)中。我尝试使用 Center Alignment 和 Distribution Fill and Spacing 10 向 UIStackView 添加元素,但我的元素一直从左侧定位。我试过改变中心。仍然没有运气。

我要实现的目标:

[------label--button------] 有 2 个元素。

[--label--button--button--] 有 3 个元素。

有没有什么方法可以不使用垫片来实现这一点。从理论上讲,我也许可以使用约束,但我不确定这是个好主意,因为元素数量不断变化。

let simpleView = UIView()
simpleView.addSubview(text)
simpleView.addSubview(button)


let leftLeading = NSLayoutConstraint(item: text, attribute:
.LeadingMargin, relatedBy: .Equal, toItem: simpleView,
attribute: .LeadingMargin, multiplier: 1.0,
constant: 10)

let leftLeading2 = NSLayoutConstraint(item: button, attribute:
.LeadingMargin, relatedBy: .Equal, toItem: simpleView,
attribute: .LeadingMargin, multiplier: 1.0,
constant: 10)

simpleView.addConstraint(leftLeading)
simpleView.addConstraint(leftLeading2)


simpleView.translatesAutoresizingMaskIntoConstraints = false
simpleView.sizeToFit()

newView.addSubview(simpleView)

let horizontalConstraint = NSLayoutConstraint(item: simpleView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: newView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
newView.addConstraint(horizontalConstraint)

let verticalConstraint = NSLayoutConstraint(item: simpleView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: newView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
newView.addConstraint(verticalConstraint)

我一定是做错了什么,因为这是我得到的(newView 是红色的,按钮是蓝色的,缺少文本标签):

enter image description here

最佳答案

创建一个 View ,将 View 居中放置在您需要的位置。然后在该 View 中,您可以插入每个元素并为每个元素提供一个程序化的 NSLayoutConstraint,其 .Leading 为 5 或元素之间您想要的任何间距。

查看[元素元素元素]

数量无关紧要。查看 NSLayoutConstraints 并确保使用 view.addConstraints。

关于swift - 如何在 UIView 中居中放置多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38838582/

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