且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用按钮取消选择集合视图中的单元格

更新时间:2023-10-29 16:29:10

存储选定的索引路径是一个坏主意,因为这些路径与集合视图耦合。如果您存储所选的 items ,则始终可以使用数组中的项目索引来确定适当的索引路径。您还可以从给定的索引路径快速确定项目。

It is a bad idea to store selected index paths, as these are coupled to the collection view. If you store the selected items then you can always determine the appropriate index path, using the item's index in the array. You can also determine an item quickly from a given index path.

在下面的代码中,我使用了类型 Item 作为基础项目,但可以是 String Int 或任何对象类型。如果您使用自己的类或结构,请确保使其符合 Equatable Hashable

In the code below I have used the type Item for your underlying item, but it could be String or Int or any object type. If you use your own class or struct, ensure you make it conform to Equatable and Hashable.

var allItems:[Item]
var selectedItems[Item]

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if collectionView == allItemsCV {
        let item = allItems[IndexPath.row]
        if let itemIndex = selectedItems.index(of:item) {
            selectedItems.remove(at:itemIndex)
            selectedItemsCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
        } else {
            selectedItems.insert(item, at: 0)
            selectedItemsCV.insertItems(at: [IndexPath(item: 0, section:0)])
        }
        allItemsCV.deselectItem(at: indexPath, animated: true)
       // cell for item at indexPath needs to render the selected/deselected 
          state correctly based on the item being in the selectedItems array

        allItemsCV.reloadItems(at: [indexPath])

    }
}

@IBAction func removeButtonPressed(_ sender: UIButton) {
//...
    if let selectedItemPaths = selectedItemCV.indexPathsForSelectedItems {
        var allItemIndexPaths = [IndexPath]()
        var tempSelectedItems = Array(selectedItems) // Need to use a temporary copy otherwise the element indexes will change
        for itemPath in selectedItemPaths {
            let removeItem = selectedItems[itemPath.item]
            if let removeIndex = tempSelectedItems.index(of: removeItem) {
                tempSelectedItems.remove(at: removeItem)
            }
            if let allItemsIndex = allItems.index(of: removeItem) {
                allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
            }
        }
        selectedItems = tempSelectedItems // Selected items array without the removed items
        selectedItemsCV.deleteItems(at:selectedItemPaths)
        allItemsCV.reloadItems(at: allItemIndexPaths)  // Reload to update the selected status
    }
}