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

问题描述 投票:2回答:1

我有一个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我将如何更新数组/列表。

ios swift drag-and-drop uicollectionview
1个回答
0
投票

有2个IndexPaths,你必须从sourceIndexPath摆脱数组元素并将其添加到destinationIndexPath,如下:

    let item = list.remove(at: sourceIndexPath.item)
    list.insert(item, at: destinationIndexPath.item)
© www.soinside.com 2019 - 2024. All rights reserved.