Search code examples
iosswiftuistackview

UIStackView issue with Distribution


I am facing an issue with UIStackview distribution. I did horizontal UIStackView with align center and Fill Proportionally distribution. But I am not getting the exact result as per the attached image.

Here I attached xcode adaptive layout and output on the simulator image. the right and left are UIViews and it contains only background color and the center has UILabel with text. So how the intrinsic content size will work for empty UIViews and how can we achieve this?

Xcode adaptive layout image

iPhone 12 Pro max output image

Thanks in advance


Solution

  • Looking at the expected output you should be using Fill distribution instead of "Fill proportionally". Then, making both side views to have the same width should solve the issue:

        let leftSideView = UIView()
        leftSideView.backgroundColor = .yellow
        leftSideView.translatesAutoresizingMaskIntoConstraints = false
    
        let rightSideView = UIView()
        rightSideView.backgroundColor = .darkGray
        rightSideView.translatesAutoresizingMaskIntoConstraints = false
    
        stackView.addArrangedSubview(leftSideView)
        stackView.addArrangedSubview(label)
        stackView.addArrangedSubview(rightSideView)
    
        NSLayoutConstraint.activate([
            leftSideView.widthAnchor.constraint(equalTo: rightSideView.widthAnchor)
        ])
    

    The end result should be this: Screenshot

    Also, there is no need to add a fixed/constant width to the Hello text because UILabels already have an intrinsic content size. This will also make your UI more future-proof: You might want to localize your app in the future and the "Hello" text will be larger or shorter depending on the language.