toiavalle
toiavalle

Reputation: 434

Swift tableView.reloadRows deleting cells

Requirement;

I have a static UITableView and I'm trying to open a pickerview when one of the cells is clicked. I change the size with heightForRowAt so when the cell is clicked I need to reload it so that the size changes. If I use reloadData() it works perfectly (I want to use reloadRows so I can add animation)

Issue:

when I try reloadRows(at..., with: .automatic) the rows simply disappear. If I reloadRows in viewWillAppear nothing changes, the row does not disappear.

Code:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(indexPath)
    if colorCelllExpandedIndex != nil{
        let prev = colorCelllExpandedIndex
        colorCelllExpandedIndex = nil
        tableView.reloadRows(at: [prev!], with: .automatic)
        //tableView.reloadData()
    } else {
        colorCelllExpandedIndex = indexPath
        colorCell.frame.size.height = CGFloat(colorCellExpandedHeight)
        tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
    }
    
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    
    if indexPath == colorCelllExpandedIndex {
        return CGFloat(colorCellExpandedHeight)
    } else {
        if indexPath.row == 1 {
            return CGFloat(colorCellRegularHeight)
        }
        return UITableViewAutomaticDimension
    }
}

Screen Images:

before and after clicking the color button

How it looks like if I use reloadData

Upvotes: 2

Views: 1361

Answers (1)

mugby
mugby

Reputation: 151

It seems that there are some issues with functions such as reloadRows(at:with:) when using a static UITableView, there is a similar question in this SO question without resolution.

I was able, however, to update the cell height by implementing the next functions:

tableView.beginUpdates()
tableView.endUpdates()

So an approach you can take could be the following:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(indexPath)
    if colorCelllExpandedIndex != nil{
        colorCelllExpandedIndex = nil
    } else {
        colorCelllExpandedIndex = indexPath
    }
    tableView.beginUpdates()
    tableView.endUpdates()

}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath == colorCelllExpandedIndex {
        return CGFloat(colorCellExpandedHeight)
    } else {
        if indexPath.row == 0 {
            return CGFloat(colorCellRegularHeight)
        }
        return UITableViewAutomaticDimension
    }
}

This is inspired in one of the answers provided in another SO question regarding hiding cells in static table views.

Upvotes: 2

Related Questions