跨部门重新排序行时无效更新

时间:2016-10-16 18:00:16

标签: ios swift uitableview

我尝试在跨部分重新排序某些UITableViewCells时尝试更新我的模型,但收到错误:

  

无效更新:第0部分中的行数无效   更新(10)后必须包含在现有部分中的行   等于之前该部分中包含的行数   更新(10),加上或减去插入或删除的行数   该部分(0插入,0删除)和加号或减号的数量   移入或移出该部分的行(0移入,1移出)。

我有以下代码,我认为我正在删除并正确插入行? (但显然不是;-))

    // Update the data model according to edit actions delete or insert.
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
    let fromIndexPath = NSIndexPath(forRow: indexPath.row, inSection: indexPath.section)

    if editingStyle == UITableViewCellEditingStyle.Delete{
        playingList.removeAtIndex(fromIndexPath.row);
    }
}

    // Process the row move. This means updating the data model to correct the item indices.
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
{
    let moveFrom = NSIndexPath(forRow: sourceIndexPath.row, inSection: sourceIndexPath.section)
    let moveTo = NSIndexPath(forRow: destinationIndexPath.row, inSection: destinationIndexPath.section)

    // swap the data between the 2 arrays
    let dataPiece = playingList[moveFrom.section][moveFrom.row]
    playingList[moveTo.section].insert(dataPiece, atIndex: moveTo.row)
    playingList[moveFrom.section].removeAtIndex(moveFrom.row)
    // Do the move between the table view rows
    playerTableView.moveRowAtIndexPath(moveFrom, toIndexPath: moveTo)
}

1 个答案:

答案 0 :(得分:1)

您的问题是您正在呼叫moveRowAtIndexPath。只需更新您的数据模型即可完成。

func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
{
    let moveFrom = NSIndexPath(forRow: sourceIndexPath.row, inSection: sourceIndexPath.section)
    let moveTo = NSIndexPath(forRow: destinationIndexPath.row, inSection: destinationIndexPath.section)

    // swap the data between the 2 arrays
    let dataPiece = playingList[moveFrom.section][moveFrom.row]
    playingList[moveTo.section].insert(dataPiece, atIndex: moveTo.row)
    playingList[moveFrom.section].removeAtIndex(moveFrom.row)
}

BTW - 您的commitEditStyle方法也不正确。它正在删除整个部分的数据(但使用行而不是部分)。只需删除一行:

playingList[indexPath.section].removeAtIndex(indexPath.row)