I 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
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
}