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

时间:2017-10-05 19:20:10

标签: ios swift uistackview

我有一个包含UIStackView的UIScrollView,我添加了视图,如果UIStackView需要比屏幕更多的空间,那么它将滚动到UIScrollView。

我能够在视图上设置不变的高度,但我还需要在它们上设置一个特定的宽度,以便它们具有特定的宽度,并且也在堆栈视图中居中。

像这样的东西,除了widthAnchor不起作用。

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
    }

}

1 个答案:

答案 0 :(得分:5)

UIStackView上的alignment属性确定其布局如何垂直到其轴。默认情况下,UIStackView的对齐方式为fill。在约束条件中,fill就像为每个排列的子视图添加约束(在这种情况下)堆栈视图的左右边缘。这些隐式约束可能会导致您的问题。 解决方案:设置stackView.alignment = leadingcentertrailing,具体取决于您所需的效果