Paul Lecomte
Paul Lecomte

Reputation: 131

Insert several same objects in the same stackview

I would like to insert in the same stackview, four objects (stackview1, stackview2, stackview3, stackview3) that are given by the same function setupIngredientStackView(). But when I run my code, the simulator displays just one object. The others are replaced by blanks.

fileprivate func setupIngredientStackView() -> UIStackView {
    let stackView = UIStackView(arrangedSubviews: [ingredient, quantité, prix])
    stackView.distribution = .fillEqually
    stackView.axis = .horizontal
    return stackView
}

fileprivate func setupPageStackView(){
    let stackview1 = setupIngredientStackView()
    let stackview2 = setupIngredientStackView()
    let stackview3 = setupIngredientStackView()
    let stackview4 = setupIngredientStackView()
    let stackView = UIStackView(arrangedSubviews: [NomDuPlat,titleIgrendient,stackview1 ,stackview2 ,stackview3 ,stackview4 , etiquettePrixTotal,date,nombreDePersonne])

    stackView.distribution = .fillEqually
    stackView.axis = .vertical
    view.addSubview(stackView)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 80).isActive = true
    stackView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
    stackView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true

}

Upvotes: 0

Views: 1300

Answers (1)

Duncan C
Duncan C

Reputation: 131491

The problem is the contents of the child stack-views. UIViews are reference objects, so if you pass your array [ingredient, quantité, prix] to multiple stack views, you are passing the same view objects each time, which doesn't work. Only one of those stack views will have contents; the rest will be empty.

You can't use the same view object in multiple places on the screen at the same time. You need to change your setupIngredientStackView() function to create new ingredients objects for each stack view that it creates.

Upvotes: 1

Related Questions