子视图宽度锚点在 stackView 中不起作用
Childview width anchor is not working inside stackView
我正在尝试在 Stackview 中拥有最多 3 个视图,并且所有子视图都应该居中对齐
`
for _ in array{
if(stackView.subviews.count != 3){
let image : UIImageView = UIImageView()
image.backgroundColor = UIColor.orange
image.heightAnchor.constraint(equalToConstant:30).isActive=true
image.widthAnchor.constraint(equalToConstant:30).isActive=true
image.layer.cornerRadius=15
stackView.addArrangedSubview(image)
}
`
stackview 对齐为中心,分布同样为中心
如果 stackView 有一个没有前导和尾随约束的 centerX 约束,使其根据子元素的大小伸展,这就可以实现
let sta = UIStackView()
sta.translatesAutoresizingMaskIntoConstraints = false
sta.distribution = .fill
sta.axis = UILayoutConstraintAxis.horizontal
self.view.addSubview(sta)
sta.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
sta.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive=true
sta.heightAnchor.constraint(equalToConstant:30).isActive=true
for _ in 0...10 {
let image : UIImageView = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
sta.addArrangedSubview(image)
image.backgroundColor = UIColor.blue
image.heightAnchor.constraint(equalToConstant:30).isActive=true
image.widthAnchor.constraint(equalToConstant:50).isActive=true
image.layer.cornerRadius=15
}
for _ in array{
if(stackView.subviews.count != 3){
let image : UIImageView = UIImageView()
image.backgroundColor = UIColor.orange
image.heightAnchor.constraint(equalToConstant:30).isActive=true
image.widthAnchor.constraint(equalToConstant:30).isActive=true
image.layer.cornerRadius=15
stackView.addArrangedSubview(image)
}
` stackview 对齐为中心,分布同样为中心
如果 stackView 有一个没有前导和尾随约束的 centerX 约束,使其根据子元素的大小伸展,这就可以实现
let sta = UIStackView()
sta.translatesAutoresizingMaskIntoConstraints = false
sta.distribution = .fill
sta.axis = UILayoutConstraintAxis.horizontal
self.view.addSubview(sta)
sta.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true
sta.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive=true
sta.heightAnchor.constraint(equalToConstant:30).isActive=true
for _ in 0...10 {
let image : UIImageView = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
sta.addArrangedSubview(image)
image.backgroundColor = UIColor.blue
image.heightAnchor.constraint(equalToConstant:30).isActive=true
image.widthAnchor.constraint(equalToConstant:50).isActive=true
image.layer.cornerRadius=15
}