简体   繁体   English

迭代 StackView,Swift

[英]Iterate StackView, Swift

I have a custom cell composed by 3 StackView.我有一个由 3 StackView 组成的自定义单元格。 Each one of them has a title, a description and an image, horizontally.他们每个人都有一个标题,一个描述和一个图像,水平。 I have to fill this cell with an Array, it could be made of max 3 elements, but it could have 2 or 1. So in my viewModel I'm treating this array like this...我必须用一个数组填充这个单元格,它最多可以由 3 个元素组成,但它可以有 2 个或 1 个。所以在我的 viewModel 中,我像这样对待这个数组......

let firstItem = myArray[0]
let secondItem = myArray[1]
let thirdItem = myArray[2]

And I fill the field with firstItem.name firstItem.description ... For each one of them (not the best approach I guess) Then I made some check if index exist, if it doesn't I delete the StackView, I set manually some constraints and I fit the cell to the content ( If I have 2 elements the cell is shorter, If I have 3 elements the cell is bigger).我用firstItem.name firstItem.description填充该字段......对于它们中的每一个(不是我猜的最佳方法)然后我检查索引是否存在,如果不存在我删除 StackView,我手动设置一些约束,我使单元格适合内容(如果我有 2 个元素,则单元格更短,如果我有 3 个元素,则单元格更大)。

This is a piece of code after I check that index 3 doesn't exist:这是我检查索引 3 不存在后的一段代码:

self.stackView.removeFromSuperview()
self.ownConstraints.constant = value (20 for example)

My question is, what is the best approach to achieve this?我的问题是,实现这一目标的最佳方法是什么? With cell I usually append item with a for cycle one by one, but I'm not familiar with this approach on StackView inside a Cell.对于单元格,我通常使用 append 项目一个一个地循环,但我不熟悉单元格内 StackView 上的这种方法。

This is what I have done with cell (a series of cell with 1 name and 1 description):这就是我对 cell 所做的(一系列具有 1 个名称和 1 个描述的单元格):

for (element) in myArray {
   self.cellArray.append( elementName , elementDescription ) 
}
// hide all items in stackView
    stackView.arrangedSubviews.forEach({ $0.isHidden = true })

    // add or update arrangedSubviews
    for (index, element) in myArray.enumerated() {
        if index >= stackView.arrangedSubviews.count - 1 {
            stackView.addArrangedSubview(UILabel())
        }
        (stackView.arrangedSubviews[index] as? UILabel)?.text = element
        stackView.arrangedSubviews[index].isHidden = false
    }

I would hide all subviews in stackView and only show subviews if content is available in your viewModel.我会隐藏 stackView 中的所有子视图,并且仅在您的 viewModel 中有内容时才显示子视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM