如何在Swift 3中获取收集单元的所有索引?

时间:2018-07-12 09:24:57

标签: ios swift uicollectionview uicollectionviewcell

我在collectionView单元格中有一个数组。起始索引为[0,3],最后索引为5,3。我将如何获得[0,3],[5,3]之间的垂直索引。像swift 3的collectionView单元中的[1,3],[2,3],[3,3],[4,3]?

1 个答案:

答案 0 :(得分:0)

这是一个解决方案,它为收集视图构建所有有效索引路径的列表,然后仅过滤起始索引和结束索引之间的路径:

func findIndexes(from collectionView: UICollectionView, between startIndex: IndexPath, and endIndex: IndexPath) -> [IndexPath] {

    // build the list of all possible index paths
    let allIndexPaths = (0..<collectionView.numberOfSections).flatMap { section in
        return (0..<collectionView.numberOfItems(inSection: section)).map { item in
            return IndexPath(item: item, inSection: section)
        }
    }

    // filter the ones in range
    return filteredIndexPaths = allIndexPaths.filter { indexPath in
        return startIndex < indexPath && indexPath < endIndex
    }
}