Home > Blockchain >  How to make Vertical StackView subviews (same specific heights) start from TOP, Swift?
How to make Vertical StackView subviews (same specific heights) start from TOP, Swift?

Time:08-14

I'm creating a vertical UIStackView where arranged subviews will start from top. Subviews quantity will be 5 at most. Here are my expectation, reality and code. Any Idea?

Expectation

enter image description here

Current situation

enter image description here

Code

var homeVStack: UIStackView = {
    let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.alignment = .top
    stackView.distribution = .equalSpacing
    stackView.spacing = 20
    stackView.translatesAutoresizingMaskIntoConstraints = false
    return stackView
}()

private func loadData() {
    if let homeFormList = data?.homeTeamForm {
        for homeForm in homeFormList {
            let teamFormView = SimpleScoreView()
            teamFormView.teamForm = homeForm
            teamFormView.heightAnchor.constraint(equalToConstant: 50).isActive = true
            teamFormView.backgroundColor = .yellow
            homeVStack.addArrangedSubview(teamFormView)
        }
    }
}

CodePudding user response:

what are the constraints of homeVStack? make it center horizontally and vertically in super View.

CodePudding user response:

Use empty view like UIView() on your last arranged view. It should be made larger than its intrinsic size.

var homeVStack: UIStackView = {
    let stackView = UIStackView()
    stackView.axis = .vertical
    stackView.alignment = .fill // default is .fill
    stackView.distribution = .equalSpacing
    stackView.spacing = 20
    stackView.translatesAutoresizingMaskIntoConstraints = false
    return stackView
}()

private func loadData() {
    if let homeFormList = data?.homeTeamForm {
        for homeForm in homeFormList {
            let teamFormView = SimpleScoreView()
            teamFormView.teamForm = homeForm
            teamFormView.heightAnchor.constraint(equalToConstant: 50).isActive = true
            teamFormView.backgroundColor = .yellow
            homeVStack.addArrangedSubview(teamFormView)
        }
    }

    homeVStack.addArrangedView(UIView()) // Important
}

Above code make your stack view layout like this. UIView should be stretched than SimpleScoreView's intrinsic size

enter image description here

Current Situation image said homeVStacks constraints are top, bot, leading and trailing to its superview with equal spacing so second SimpleScoreView is on bottom.

You can choice two options

  1. You should make spacing with another UI like transparent UIView for stretched instead of SimpleScoreView bottom layout.

  2. Remove stack view's bottom constraint to root view and make height by contents(arranged view)

  • Related