[英]Center views horizontally of different widths inside a UIStackView
不,你不能。 来自苹果的Doc
堆栈视图使用“自动布局”来定位和调整其排列的视图大小。 堆栈视图将第一个和最后一个排列的视图与其沿着堆栈轴的边缘对齐。
In a horizontal stack, this means the first arranged view's leading edge is pinned to the stack's leading edge, and the last arranged view's trailing edge is pinned to the stack's trailing edge.
您可以使用约束 。
在那里添加视图后,我可以使UIStackView自动增长宽度
代码
class StackSampleViewController:UIViewController {
@IBOutlet weak var stackView: UIStackView! //Keep center auto grow with subviews @IBAction func touchUpAdd(_ sender: Any) { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.heightAnchor.constraint(equalToConstant: 20.0).isActive = true if (stackView.subviews.count % 2) == 0 { view.widthAnchor.constraint(equalToConstant: 100).isActive = true view.backgroundColor = .black } else { view.widthAnchor.constraint(equalToConstant: 50).isActive = true view.backgroundColor = .red } stackView.addArrangedSubview(view) }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.