簡體   English   中英

更改UICollectionViewCell位置后如何正確移動數組項

[英]How to properly move array item when `UICollectionViewCell` position is changed

我有一個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被調用,我將如何更新數組/列表。

有兩個IndexPath ,您必須擺脫sourceIndexPath的數組元素並將其添加到destinationIndexPath ,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM