Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 插入新单元格时TableView更新错误_Swift_Uitableview - Fatal编程技术网

Swift 插入新单元格时TableView更新错误

Swift 插入新单元格时TableView更新错误,swift,uitableview,Swift,Uitableview,我有一个UITableView,它是从所有一个xib文件填充的。我试图在单击单元格时在单元格下方插入另一个单元格(该单元格将由单独的xib填充)。这样做的想法是制作一种下拉菜单 我当前正在使用下面的代码,以便在选择单元格时运行函数: func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //below prints the name of the selec

我有一个UITableView,它是从所有一个xib文件填充的。我试图在单击单元格时在单元格下方插入另一个单元格(该单元格将由单独的xib填充)。这样做的想法是制作一种下拉菜单

我当前正在使用下面的代码,以便在选择单元格时运行函数:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //below prints the name of the selected user
        print(name[indexPath.row])

        var contactNum = ""

        //below inserts a new cell into the table view, below the selected cell
        // Update Table Data
        myTableView.beginUpdates()
        myTableView.insertRowsAtIndexPaths([
            NSIndexPath(forRow: (indexPath.row)+1, inSection: 0)
            ], withRowAnimation: .Automatic)
        let cell = myTableView.dequeueReusableCellWithIdentifier("DDOCell")
        myTableView.endUpdates()

        //below reloads the table view after changes are made
        myTableView.reloadData()

    }
但是继续得到以下错误

'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

有人知道为什么在所选数据源下没有创建具有不同数据源的新单元格的问题吗?

之所以会出现错误,是因为在调用
insertrowsatindepath
之前没有先更新数据模型。鉴于您的
打印
声明,您可能需要(在Swift 3中):

请注意,此处不需要调用
beginUpdates
endUpdates
,因为您只调用了一次
delete | insert | reloadRowsAtIndexPaths


还要注意,您决不能在
cellForRowAt
之外调用
dequeueReusableCellWithIdentifier
。如果在任何其他方法中确实需要表中的单元格,例如
didSelectRowAt
,请使用
cellForRow(at:)

因为在调用
insertrowsatindepath
之前没有先更新数据模型,所以会出现错误。鉴于您的
打印
声明,您可能需要(在Swift 3中):

请注意,此处不需要调用
beginUpdates
endUpdates
,因为您只调用了一次
delete | insert | reloadRowsAtIndexPaths


还要注意,您决不能在
cellForRowAt
之外调用
dequeueReusableCellWithIdentifier
。如果您确实需要使用任何其他方法(如
didSelectRowAt
)从表中提取单元格,请使用
cellForRow(at:)

不相关,但您确实需要从Swift 2迁移。不相关,但您确实需要从Swift 2迁移。
name.insert("some new name", at: indexPath.row + 1)