1

I'd like to know what's the cleanest way to remove a view from a stack view if a certain property in my data model is nil. I have a table view which is populated by prototype cells. They look like this:

enter image description here

The second label text contains an optional value which may be nil; I want to hide the label if it's nil. Should I call removeArrangedSubview inside the cellForRow table view cell method or inside the CustomTableViewCell class with a function?

Cesare
  • 9,139
  • 16
  • 78
  • 130

1 Answers1

1

I want to hide the label if [optional value] is nil

You should set label's hidden property to true rather than removing it from arranged subview list of stack layout in order to avoid adding it back when the cell gets reused for a different row.

It is mostly a matter of preference where you do it. If most of your cell setup code is in the cellForRow function, you should hide and unhide the label from that function as well:

if let labelText = model.getTextForMyLabel(indexPath.row) {
    cell.label.text = labelText
    cell.label.hidden = false
} else {
    cell.label.hidden = true
}

If you have a setter for label text in the code for your CustomTableViewCell, you can use the same approach to set the label's hidden property along with its text.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks! Very quick question: do labels have a setter for their `text` property called every time I update their text? – Cesare Jul 08 '17 at 09:33
  • @Cesare There is a good chance that the setter for label's `text` property checks if the current label text matches the new text that you are trying to set, and skips the actual setting if the new text is the same as the current text. – Sergey Kalinichenko Jul 08 '17 at 09:39