Aaron Bratcher
Aaron Bratcher

Reputation: 6451

Why isn't my label hiding?

I have a tableViewCell with a stackView. I'm trying to make it a collapsable cell. I can successfully set the hidden state of the 2nd label during tableView:cellForRowAt:

However if I change the hidden state in response to a tap of the cell, visibility doesn't change on-screen.

UIView.animate(withDuration: 0.25) { [unowned self] in
    self.disclaimers.isHidden = !cellItem.isExpanded
}

The cellItem.isExpanded property is toggled properly as is the label .isHidden property. Just no change on-screen.

I know this is already on the main thread as tableView:didSelectRowAt: is called on the main thread. But to cover myself I tried wrapping the line with a DispatchQueue.main.async { } call instead of the UIView.animate. No change.

Any ideas?

Full project is here if you're willing: https://github.com/AaronBratcher/TableViewTester

Issue is in DisclaimersCell.swift. Line 33

Upvotes: 0

Views: 82

Answers (1)

DonMag
DonMag

Reputation: 77452

Couple issues...

You should never call .dequeueReusableCell anywhere other than in cellForRowAt. You do that in TableViewController.swift -> didSelectRowAt ... which creates a new instance of the cell, not the existing instance in your table. Change your guard line to:

    guard var cellItem = helper.cellForRowAtIndexPath(indexPath) as? TableViewExpandableCellItem
        , let cell = tableView.cellForRow(at: indexPath) as? TableViewExpandableCell
        , cellItem.shouldExpand
        else { return }

That way, tableView.cellForRow(at: indexPath) will return the existing cell.

Next, animating the setting of .isHidden won't give you the animation you want.

In DisclaimersCell.swift -> toggleExpansion(), change:

    UIView.animate(withDuration: 0.25) { [unowned self] in
        self.disclaimers.isHidden = !cellItem.isExpanded
    }

to simply:

    self.disclaimers.isHidden = !cellItem.isExpanded

Then, in your TableViewController didSelectRowAt function:

    cellItem.isExpanded = !cellItem.isExpanded
    cell.toggleExpansion(tableViewCellItem: cellItem)

    tableView.beginUpdates()
    tableView.endUpdates()

That will tell the cell to hide/show the label, and pairing .beginUpdates() with endUpdates() will trigger the recalculation of row heights in your table, and animate the redraw.

Upvotes: 1

Related Questions