A
A
Aleksandr Govorukhin2018-07-25 21:03:31
iOS
Aleksandr Govorukhin, 2018-07-25 21:03:31

How to fix jumping cells in TableView?

Hello!
There is one problem that I still cannot solve, namely, I am struggling with smooth animation of adding new cells to the table (tableView.insertRows). The video below shows how, when opened, all cells twitch wildly, I am attaching the code:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (destinationData?[indexPath.row]) != nil {
            if(indexPath.row + 1 >= (destinationData?.count)!) {
                expandCell(tableView: tableView, index: indexPath.row)
            }
            else {
                if(destinationData?[indexPath.row+1] != nil) {
                    expandCell(tableView: tableView, index: indexPath.row)
                    // Close Cell (remove ExpansionCells)
                } else {
                    contractCell(tableView: tableView, index: indexPath.row)
                }
            }
        }
    }

    private func expandCell(tableView: UITableView, index: Int) {
        if let infoMain = destinationData?[index]?.infoMain {
            for i in 1...infoMain.count {
                destinationData?.insert(nil, at: index + 1)
                tableView.insertRows(at: [IndexPath(row: index + i, section: 0)] , with: .bottom)
            }
        }
    }
    
    private func contractCell(tableView: UITableView, index: Int) {
        if let infoMain = destinationData?[index]?.infoMain {
            for _ in 1...infoMain.count {
                destinationData?.remove(at: index + 1)
                tableView.deleteRows(at: [IndexPath(row: index + 1, section: 0)], with: .top)
            }
        }
    }

Video
https://yadi.sk/i/sgmVtjpD3Zadbc

I tried everything I could and surfed the Internet, I could not find a solution to the problem, please tell me how to fix this.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
andrew8712, 2018-07-26
@andrew8712

Wrap the contents of expandCell and contractCell in calls to tableView.beginUpdate() and tableView.endUpdate()
And of course it's better to call tableView.insertRows.... once, not every iteration. I advise you to first build an array of indices, and with them already call this method

I
iMaximus, 2018-07-26
@iMaximus

I'm too lazy to write code, but there is a method tableView.insertRows(at: IndexSet(integer: tableview.numberOfRows), withAnimation: .effectFade)
And there are a lot of videos on this topic https://www.youtube.com/watch?v= whbyVPFFh4M
https://www.youtube.com/watch?v=xhPDQ-I8Hf8

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question