UITableView单元格插入失败

时间:2017-09-16 01:44:38

标签: ios swift uitableview swift3

我正在尝试创建一个可扩展的标题视图的UITableView。当您按下标题视图内的按钮时,将执行以下功能:

func expandTheCell(_ sender: UIButton) {
    self.tableView.beginUpdates()

    if sender.isExpanded == false {

        postsArray.append("Hello")
        tableView.reloadData()
        print("Array Count: \(postsArray.count)")
        self.tableView.insertRows(at: [IndexPath.init(row: 0, section: sender.tag)], with: .fade)

    } else {
        print("test")
    }

    self.tableView.endUpdates()
}

这是一些表格视图功能:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {        
    return postsArray.count
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

当我尝试插入行时,出现以下错误:

  

由于未捕获的异常而终止应用   ' NSInternalInconsistencyException',原因:'无效更新:无效   第1节中的行数

为什么我不能插入细胞?我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为问题是由于在您的案例postsArray中,当您在点击按钮时将项目附加到postsArray时,这些部分具有相同的 dataSource数组,同样postsArray用于其他部分,因此在section 0中插入行后,section 1会抱怨我在插入操作之前和之后的行数不相同,但是{{1}不抱怨,因为它在section 0

中具有相同的行数和项数

现在可以通过两种方式解决这个问题:

第一种方法是你也可以插入其他部分的行,然后所有部分的行数与postsArray

中的元素数相同

第二种方式是所有部分都有不同的dataSource数组,例如第1部分为postsArray,第2部分为postsArray1,其他部分为{1}。现在在这种情况下你不需要为其他部分插入行,因为每个部分都有不同的dataSource数组,更改一个不会影响其他部分。

我做了一个简单的项目来证明上述理论:

postsArray2

希望这会有所帮助。

相关问题