如何在更改`UICollectionViewCell`位置时正确移动数组项

时间:2018-03-05 15:49:50

标签: ios swift drag-and-drop uicollectionview

我有一个UICollectionView,用户可以在查看每个Swift拖放页面后更改单元格的位置。我决定使用一种方法来更新字符串数组,以跟踪此函数中的集合视图:

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

    let positionPreviouslyHoldingTheSelectedIndex = list[sourceIndexPath.item] 

    // put the select index in the intended destination index

    list[sourceIndexPath.item] = list[destinationIndexPath.item]


    // put the cell/index of the destination index in the selected positions old index

    list[destinationIndexPath.item] = positionPreviouslyHoldingTheSelectedIndex
}

但是上面的代码按预期更新了数组并且它变得很奇怪,一旦调用moveItemAt我将如何更新数组/列表。

1 个答案:

答案 0 :(得分:0)

有2个IndexPath,您必须从sourceIndexPath中删除数组元素并将其添加到destinationIndexPath,如下:

    let item = list.remove(at: sourceIndexPath.item)
    list.insert(item, at: destinationIndexPath.item)