1

enter image description hereI am trying to have maximum 3 views inside Stackview and all child views should be centre aligned `

     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 is centre and distribution is equally centre

Mithran
  • 301
  • 1
  • 3
  • 15

1 Answers1

3

This can be accomplished if the stackView has a centerX constraint with no leading&trailing constraints to make it stretch according to size of child elements

    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



    }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • 1
    Thanks man! it worked. my mistake i was having stack view in the storyboard with width constraint – Mithran Apr 11 '18 at 16:48