UIStackView - 想要一个百分比来定义每个项目

UIStackView - Want a percentage to define each item

我想将两个视图放入一个 UIStackView 中。我希望顶部项目始终是 space 的 30%,无论它出现在什么设备(或方向)上。因此,我希望底部视图为 70%。如何告诉 UIStackView 我想使用百分比?

Example resulting view

来自苹果文档

UIStackViewDistributionFillProportionally A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis. Views are resized proportionally based on their intrinsic content size along the stack view’s axis.

所以根据这个你应该设置 UIStackView distribution 属性 到 UIStackViewDistributionFillProportionally 并设置 intrinsic size, its.

您可以获得更多信息here and on Intrinsic content size

只需为顶视图设置一个约束。

在情节提要的文档大纲 中按住 control 从顶视图拖动到堆栈视图,然后 select Equal heights。这将使它们的高度相等。现在转到 Size Inspector,您应该会看到约束。双击它并将 multiplier 设置为 0.3。然后更新帧。

如果底部视图没有自动调整大小或者它给您一个错误提示您需要高度限制,只需重复该过程,但现在将乘数设置为 0.7。

Swift 5.2

以编程方式实现此

UIView 设置为在 UIStackView

中始终为其父视图大小的 30%
viewA.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3).isActive = true

完整代码实现:

// Configure the StackView
let stackView = UIStackView()

stackView.axis = .vertical
stackView.distribution = .fill
view.addSubview(stackView)

stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

// Configure View A
let viewA = UIView()
viewA.backgroundColor = .darkGray
viewA.translatesAutoresizingMaskIntoConstraints = false

// Configure View B
let viewB = UIView()
viewB.backgroundColor = .lightGray
viewB.translatesAutoresizingMaskIntoConstraints = false

// Add Views to StackView
stackView.addArrangedSubview(viewA)
stackView.addArrangedSubview(viewB)

// Set the height percentage multiplier to View A
viewA.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3).isActive = true