菜鸟教程小白 发表于 2022-12-11 19:49:26

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


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

<pre><code>func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

    let positionPreviouslyHoldingTheSelectedIndex = list

    // put the select index in the intended destination index

    list = list


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

    list = positionPreviouslyHoldingTheSelectedIndex
}
</code></pre>

<p>但是上面的代码按预期更新了数组,它变得很奇怪,一旦调用 <code>moveItemAt</code> 我将如何更新数组/列表。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p><code>IndexPath</code>有2个,你需要把<code>sourceIndexPath</code>中的数组元素去掉,添加到<code>destinationIndexPath</code>中,如下: </p>

<pre><code>    let item = list.remove(at: sourceIndexPath.item)
    list.insert(item, at: destinationIndexPath.item)
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 更改`UICollectionViewCell` 位置时如何正确移动数组项,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/49114298/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/49114298/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 更改 `UICollectionViewCell` 位置时如何正确移动数组项