简体   繁体   中英

How to append row in tableview swift?

I'm adding data in my model and model is assigned to tableview to reload data. But every time reloading is not looking good. so I want just last element that was added in model, should be appended in already exist tableview. Tried so many ways but getting crash when my tableview is empty.

        let lastSectionIndex = self.isGroupChat ? self.objGroupChatList!.count-1 : self.objSingleChatList!.count-1
        var lastRow = 0
        if self.isGroupChat {
            lastRow = (self.objGroupChatList?[lastSectionIndex].count ?? 1)
        } else {
            lastRow = (self.objSingleChatList?[lastSectionIndex].count ?? 1)
        }
        let IndexPathOfLastRow = IndexPath(row: lastRow-1, section: lastSectionIndex)

        self.tableView.beginUpdates()
        self.tableView.insertRows(at: [IndexPathOfLastRow], with: UITableViewRowAnimation.none)
        self.tableView.endUpdates()

This is crashing with error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (0), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

You should use insertSections for new sections. insertRows only works for existing sections.

You need to do something like,

    let section = 0 //get your section here...
    dataSource[section].append("five")
    let row = dataSource[section].count - 1
    tableView.insertRows(at: [IndexPath(row: row, section: section)], with: .none)

This is just an example of how you can get that working. Fill the gaps as per your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM