在同一个堆栈视图中插入几个相同的对象

Insert several same objects in the same stackview

我想在同一个 stackview 中插入由同一个函数 setupIngredientStackView() 给出的四个对象(stackview1、stackview2、stackview3、stackview3)。但是当我 运行 我的代码时,模拟器只显示一个对象。其他的用空格代替。

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

}

问题出在子堆栈视图的内容上。 UIView 是引用对象,因此如果您将数组 [ingredient, quantité, prix] 传递给多个堆栈视图,则每次传递的都是相同的视图对象,这是行不通的。这些堆栈视图中只有一个会有内容;其余的将是空的。

您不能同时在屏幕上的多个位置使用同一个视图对象。您需要更改 setupIngredientStackView() 函数以为其创建的每个堆栈视图创建新的成分对象。