ChildView宽度锚点在stackView中不起作用

时间:2018-04-11 12:06:33

标签: ios swift uistackview stackview

enter image description here我正在尝试在Stackview中拥有最多3个视图,并且所有子视图都应该居中对齐 `

     for _ in array{
        if(stackView.subviews.count != 3){
            let image : UIImageView = UIImageView()
            image.backgroundColor = UIColor.orange
            image.heightAnchor.constraint(equalToConstant:30).isActive=true
            image.widthAnchor.constraint(equalToConstant:30).isActive=true
            image.layer.cornerRadius=15
            stackView.addArrangedSubview(image)
        }

`   stackview alignment是中心,分布是同等中心

1 个答案:

答案 0 :(得分:2)

如果stackView具有一个没有前导和尾随约束的centerX约束,可以根据子元素的大小进行拉伸,则可以实现这一点

    let sta = UIStackView()

    sta.translatesAutoresizingMaskIntoConstraints = false

    sta.distribution = .fill

    sta.axis = UILayoutConstraintAxis.horizontal

    self.view.addSubview(sta)

    sta.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive=true

    sta.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive=true

    sta.heightAnchor.constraint(equalToConstant:30).isActive=true

    for _ in 0...10 {

            let image : UIImageView = UIImageView()
            image.translatesAutoresizingMaskIntoConstraints = false
            sta.addArrangedSubview(image)
            image.backgroundColor = UIColor.blue
            image.heightAnchor.constraint(equalToConstant:30).isActive=true
            image.widthAnchor.constraint(equalToConstant:50).isActive=true
            image.layer.cornerRadius=15



    }
相关问题