StackView constraints with UIViews

I'm trying to setup a stackview in the middle of the screen with a padding of 20 to the left an right. Inside, I want to place two custom UIViews, but I don't quit understand how to do it. I tried giving the UIViews their respective Height's and Width's but I got nothing.

I believe the stack view has all the correct constraints. Here's the code:

func setupTeamViews() {
    view.addSubview(teamsStackView)
    
    teamsStackView.distribution = .fill
    teamsStackView.axis = .vertical
    teamsStackView.spacing = 20
    teamsStackView.alignment = .fill
    
    NSLayoutConstraint.activate([
        teamsStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
        teamsStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
        teamsStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        teamsStackView.heightAnchor.constraint(equalToConstant: 420)
    ])
    
    let height = CGFloat((teamsStackView.frame.height / 2) - 20)
    let width = CGFloat((teamsStackView.frame.width - 20))
    
    firstTeamView = ATTeamView(width: width, height: height)
    firstTeamView.changeColor(color: .lightBlue)
    firstTeamView.setTeamName(name: "Tobias")
    firstTeamView.setNewPoints(points: "0")
    
    secondTeamView = ATTeamView(width: width, height: height)
    secondTeamView.changeColor(color: .white)
    secondTeamView.setTeamName(name: "Valen")
    secondTeamView.setNewPoints(points: "0")
    
    teamsStackView.addArrangedSubview(firstTeamView)
    teamsStackView.addArrangedSubview(secondTeamView)
}

How does a stackview work with UIview's? As far I understand, UIViews don't have intrinsicContentSize, but I don't know how to deal with that.

2 answers

  • answered 2020-07-05 03:15 shane

    In stead of doing it programmatically you can add two container views attach them to your view controller, and then active them with the alpha.

    This will make constraints easier and you can still program anything extra you would like

    myView1.alpha = 1 // activate
    myView2.alpha = 0 // deactivate
    

  • answered 2020-07-05 21:39 Tobias Ruano

    My code wasn't working because I've forgotten to set teamsStackView.translatesAutoresizingMaskIntoConstraints = false