当轴垂直时,在UIStackView的子视图上设置恒定宽度



我有一个UIScrollView,它包含一个UIStackView,我会向它添加视图,如果UIStackView需要比屏幕更多的空间,那么它会因为UIScrollView而滚动。

我可以在视图上设置恒定的高度,但我也需要在它们上设置特定的宽度,这样它们就有了特定的宽度并且也在堆栈视图中居中。

像这样的东西,除了宽度锚不起作用。

import UIKit
class ViewController: UIViewController {
let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.backgroundColor = .gray
return sv
}()
let stackView: UIStackView = {
let sv = UIStackView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.axis = .vertical
return sv
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
scrollView.addSubview(stackView)
stackView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
let view1 = UIView()
view1.backgroundColor = .red
let view2 = UIView()
view2.backgroundColor = .blue
let view3 = UIView()
view3.backgroundColor = .green
let view4 = UIView()
view4.backgroundColor = .purple
stackView.addArrangedSubview(view1)
stackView.addArrangedSubview(view2)
stackView.addArrangedSubview(view3)
stackView.addArrangedSubview(view4)
view1.heightAnchor.constraint(equalToConstant: 200).isActive = true
view2.heightAnchor.constraint(equalToConstant: 300).isActive = true
view3.heightAnchor.constraint(equalToConstant: 420).isActive = true
view4.heightAnchor.constraint(equalToConstant: 100).isActive = true
// This does not work.
//        view1.widthAnchor.constraint(equalToConstant: 40).isActive = true
}
}

UIStackView上的alignment属性决定其布局如何垂直于其轴工作。默认情况下,UIStackView的对齐方式为fill。在约束方面,fill类似于为每个排列的子视图向堆栈视图的左边缘和右边缘添加约束(在这种情况下)。这些隐含的约束可能会导致您的问题解决方案:根据所需效果设置stackView.alignment =leadingcentertrailing

相关内容

  • 没有找到相关文章

最新更新