Search code examples
iosswiftuicollectionviewnsindexpath

Swift iOS. How can I get indexPath's of cells in UICollectionView


I need to update collectionView when without reloadData() (To animatedly insert and delete cells) So I want to get array of indexPaths of cells.


Solution

  • To get the array of index paths for currently visible UICollectionView cells just call

    collectionView.indexPathsForVisibleItems()
    

    To get all cells you can create your own array using the data source methods.

    var indexPaths: [NSIndexPath] = []
    for s in 0..<collectionView.numberOfSections() {
        for i in 0..<collectionView.numberOfItemsInSection(s) {
            indexPaths.append(NSIndexPath(forItem: i, inSection: s))
        }
    }
    

    Here's the Swift5 syntax!

        var allIPs: [IndexPath] = []
        for s in 0..<coll.numberOfSections {
            for i in 0..<coll.numberOfItems(inSection: s) {
                allIPs.append(IndexPath(item: i, section: s))
            }
        }