[英]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.