2

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 ) 
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
ConteOlaf
  • 75
  • 2
  • 8
  • Your question isn't very clear and you didn't enough code to understand your question. I would embed your stackViews inside of another stackView. – Rob C Apr 16 '20 at 08:43

1 Answers1

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

Stefan Wieland
  • 246
  • 2
  • 4
  • Your solution is really good! May I ask some clarification? Let's say my cell is made of 6 Outlet (Three title and Three description). I embedded everything in a StackView and I hide it with your first line of code. Then I iterate through my array , if index >= stackView.arrangedSubview.count - 1 , I add a label? Then I add text through my element? How do I manage this if I already have some Outlet? Do I need all 6, or just 1 title and 1 description and I Iterate through it? How do I add text both in title and description? – ConteOlaf Apr 16 '20 at 21:23
  • I mean, in my cell I have a structured design with 6 label and 3 images, can I add them programmatically like this? – ConteOlaf Apr 16 '20 at 21:34