简体   繁体   English

如何在tableview swift中追加行?

[英]How to append row in tableview swift?

I'm adding data in my model and model is assigned to tableview to reload data. 我在模型中添加数据,并将模型分配给tableview以重新加载数据。 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. 所以我只想在模型中添加的最后一个元素应该添加到已经存在的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. 由于未捕获的异常“ NSInternalInconsistencyException”而终止应用程序,原因:“无效的更新:无效的节数。 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).' 更新(1)之后表视图中包含的节数必须等于更新(0)前表视图中包含的节数,加上或减去插入或删除的节数(插入的0,0删除)。”

You should use insertSections for new sections. 您应该将insertSections用于新部分。 insertRows only works for existing sections. insertRows仅适用于现有部分。

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. 根据您的代码填补空白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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