Search code examples
iosswiftuistackviewstackview

StackView Not Aligning To The Left Programmatically


My StackView that I am making programmatically is looking like this:

Two Subviews:

Three Subviews:

Four Subviews:

This is my code:

    cameraButton.setImage(UIImage(named: "blueCamera"), for: .normal)
    cameraButton.addTarget(self, action: #selector(cameraTapped), for: .touchUpInside)
    cameraButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true
    calenderButton.setImage(UIImage(named: "calender"), for: .normal)
    calenderButton.addTarget(self, action: #selector(calanderTapped), for: .touchUpInside)
    calenderButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true

    stackView.frame = CGRect(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollViewHeight)
    stackView.axis = .horizontal
    stackView.spacing = 5
    stackView.semanticContentAttribute = .forceLeftToRight
    stackView.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
    stackView.distribution = .equalSpacing // .fillEqually .fillProportionally .equalSpacing .equalCentering
    stackView.addArrangedSubview(calenderButton)
    stackView.addArrangedSubview(cameraButton)
    stackView.backgroundColor = UIColor(red: 0.161, green: 0.165, blue: 0.188, alpha: 1.00)
    scrollView.addSubview(stackView)

What is the problem: The StackView is not aligning the subviews to the left.

What I am trying to achieve:

I want all the subviews aligned to the left, I tried to do this with stackView.semanticContentAttribute = .forceLeftToRight, but that didn't seem to achieve much.


Solution

  • Set:

        stackView.alignment = .leading 
    

    And remove This:

        stackView.distribution = .equalSpacing
    

    Your code then will be like:

        cameraButton.setImage(UIImage(named: "blueCamera"), for: .normal)
        cameraButton.addTarget(self, action: #selector(cameraTapped), for: .touchUpInside)
        cameraButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true
        calenderButton.setImage(UIImage(named: "calender"), for: .normal)
        calenderButton.addTarget(self, action: #selector(calanderTapped), for: .touchUpInside)
        calenderButton.widthAnchor.constraint(equalToConstant: 70.0).isActive = true
    
        stackView.frame = CGRect(x: 0, y: 0, width: scrollView.frame.size.width, height: scrollViewHeight)
        stackView.axis = .horizontal
        stackView.spacing = 5
        stackView.alignment = .leading    
        stackView.addArrangedSubview(calenderButton)
        stackView.addArrangedSubview(cameraButton)
        stackView.backgroundColor = UIColor(red: 0.161, green: 0.165, blue: 0.188, alpha: 1.00)
        scrollView.addSubview(stackView)