我有一个由5个元素组成的UIStackView。我希望中心的比其他人大(如下图)。
我如何创建UIStackView()
stackView.axis = UILayoutConstraintAxis.horizontal
stackView.distribution = UIStackViewDistribution.fillEqually
stackView.alignment = UIStackViewAlignment.bottom
stackView.spacing = 0.0
stackView.addArrangedSubview(supportedServicesView)
stackView.addArrangedSubview(incidentView)
stackView.addArrangedSubview(contactUsView)
stackView.addArrangedSubview(moreView)
stackView.addArrangedSubview(moreView2)
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
stackView.anchor(nil, left: self.view.leftAnchor, bottom: self.view.bottomAnchor, right: self.view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 90, rightConstant: 0, widthConstant: 0, heightConstant: 0)
我如何创建自定义UIViews子视图位置;
override func updateConstraints() {
logoImage.anchor(self.topAnchor, left: self.leftAnchor, bottom: nil, right: self.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
label.anchor(self.logoImage.bottomAnchor, left: self.leftAnchor, bottom: nil, right: self.rightAnchor, topConstant: 10, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
super.updateConstraints()
}
编辑: 当我将宽度锚点添加到居中视图时,它会获得更高的宽度,但由于高度相同,它看起来不会更大。
contactUsView.widthAnchor.constraint(equalToConstant: self.view.frame.width / 5).isActive = true
编辑2:当我对UIStackView中的任何视图赋予高度约束时,Stackviews位置(仅限高度)会更改为我赋予视图高度锚点的值。
答案 0 :(得分:4)
我刚在操场上实现了这个例子。
UIStackView使用内在内容大小来计算如何将其排列的子视图放在堆栈视图中,并考虑轴,分布,间距等。
因此,如果您同时添加高度和宽度约束,您应该看到它正常工作。请参阅下面输出的示例和屏幕截图。
//: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
let stackview = UIStackView(frame: CGRect(x: 0, y: 0, width: 500, height: 150))
stackview.backgroundColor = .white
let colours: [UIColor] = [
.blue,
.green,
.red,
.yellow,
.orange
]
for i in 0...4 {
let view = UIView(frame: CGRect.zero)
view.backgroundColor = colours[i]
view.translatesAutoresizingMaskIntoConstraints = false
if i == 2 {
view.heightAnchor.constraint(equalToConstant: 130).isActive = true
} else {
view.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
view.widthAnchor.constraint(equalToConstant: 75)
stackview.addArrangedSubview(view)
}
stackview.axis = .horizontal
stackview.distribution = .fillEqually
stackview.alignment = .bottom
stackview.spacing = 0.5
PlaygroundPage.current.liveView = stackview
您可以将此代码直接放入游乐场并调整间距,分布等设置以获得所需的输出。