【发布时间】:2020-04-25 00:30:02
【问题描述】:
我正在尝试创建一个自定义 UIStackView 函数,该函数采用百分比值来填充轴边界。我正在努力正确实施这一点。我已经尝试了一些东西,但它不能正常工作。有没有办法可以实现这个?还是已经有内置的方法?
extension UIStackView {
func setHeightPercentageFill(values: [CGFloat]) {
guard values.count == arrangedSubviews.count else { return }
axis = .vertical
distribution = .fillProportionally
for i in 0..<arrangedSubviews.count {
arrangedSubviews[i].heightAnchor.constraint(equalToConstant: bounds.height * values[i]).isActive = true
}
}
}
Desired Usage(将每个子视图的高度设置为 20%、40%、30%、10%)
let stack = UIStackView(arrangedSubviews: [view1, view2, view3, view4])
addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.topAnchor.constraint(equalTo: topAnchor).isActive = true
stack.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
stack.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
stack.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
stack.setHeightPercentageFill(values: [0.20, 0.40, 0.30, 0.10])
【问题讨论】:
标签: ios swift uikit uistackview