简体   繁体   中英

Iterate StackView, Swift

I have a custom cell composed by 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...

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).

This is a piece of code after I check that index 3 doesn't exist:

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.

This is what I have done with cell (a series of cell with 1 name and 1 description):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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