OGeek|极客世界-中国程序员成长平台

标题: ios - 更改 `UICollectionViewCell` 位置时如何正确移动数组项 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:49
标题: ios - 更改 `UICollectionViewCell` 位置时如何正确移动数组项

我有一个 UICollectionView,用户可以在查看每个 Swift 拖放页面后更改单元格的位置。我确定了一种能够更新字符串数组以跟踪此函数中的 Collection View 的方法:

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



Best Answer-推荐答案


IndexPath有2个,你需要把sourceIndexPath中的数组元素去掉,添加到destinationIndexPath中,如下:

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

关于ios - 更改 `UICollectionViewCell` 位置时如何正确移动数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114298/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4