looping through all cells in UICollectionview

会有一股神秘感。 提交于 2019-12-04 03:33:50

You cannot loop through non-visible cells because those cells don't exist. UICollectionView, like UITableView, reuses cells as soon as they are offscreen. I.e., if you scroll down, it takes a cell that has been scrolled off and uses it for a "new" cell about to be scrolled into view.

If you wish to hold state for an entry in your collection, you'll have to store it separately from the cell itself. For example, an NSArray of structs (or custom NSObjects) that map to the indexPath.row value.

A more important question for you specifically would be: What are you trying to achieve in your for loop?

Let me know if you need more information or sample code.

Swift 4+

func getAllCells() -> [UICollectionViewCell] {

    var cells = [UICollectionViewCell]()
    // assuming tableView is your self.tableView defined somewhere

    for i in 0...self.numberOfSections-1
    {
        for j in 0...self.numberOfItems(inSection: i) - 1
        {
            if let cell = self.cellForItem(at: NSIndexPath(row: j, section: i) as IndexPath) {

                cells.append(cell)
            }

        }
    }
    return cells
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!