我正在尝试创建一个自定义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
}
}
}
所需用法(将每个子视图的高度设置为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])
您的代码不起作用,因为stackView的大小取决于其子视图的固有内容大小。您有鸡/鸡蛋的情况。 stackView的高度取决于子视图的高度,而子视图的高度取决于stackView的高度。您需要告诉stackView您想要的高度是什么。
将高度传递到setHeightPercentageFill(values:)
对我有用:
extension UIStackView {
func setHeightPercentageFill(values: [CGFloat], height: CGFloat) {
guard values.count == arrangedSubviews.count else { return }
axis = .vertical
distribution = .fillProportionally
for i in 0..<arrangedSubviews.count {
arrangedSubviews[i].heightAnchor.constraint(equalToConstant: height * values[i]).isActive = true
}
}
}
请注意,我在情节提要中将容器高度定义为128。您需要确保将您的stackView约束为固定的高度。
class ViewController: UIViewController {
lazy var view1: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .red
return view
}()
lazy var view2: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .orange
return view
}()
lazy var view3: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .blue
return view
}()
lazy var view4: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .yellow
return view
}()
@IBOutlet weak var container: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let stack = UIStackView(arrangedSubviews: [view1, view2, view3, view4])
container.addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.topAnchor.constraint(equalTo: container.topAnchor).isActive = true
stack.leftAnchor.constraint(equalTo: container.leftAnchor).isActive = true
stack.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
stack.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true
stack.setHeightPercentageFill(values: [0.20, 0.40, 0.30, 0.10], height: container.frame.size.height)
}
}