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