[英]Looping through CollectionView Cells in Swift
I'm wondering how to loop through all of my CollectionView Cells that currently visible. 我想知道如何遍历当前可见的所有CollectionView单元格。
In Objective C, I would achieve this concept seen below: 在Objective C中,我将实现以下概念:
for(UICollectionView *cell in collectionView.visibleCells){
}
I've tried changing this into swift: 我已经尝试将其更改为swift:
for cell:MyCollectionViewCell in self.collectionView.visibleCells() as cell:MyCollectionViewCell {
}
However I get the following error: 但是我收到以下错误:
Type 'MyCollectionViewCell' does not conform to protocol 'SequenceType'
How do I loop through all my CollectionViewCells 如何遍历所有CollectionViewCells
They way you're using as
in that loop is trying to cast the array of visible cells to a single collection view cell. 你正在使用它们的方式, as
在该循环中试图将可见单元格数组转换为单个集合视图单元格。 You want to cast to an array: 您想要转换为数组:
for cell in cv.visibleCells() as [UICollectionViewCell] {
// do something
}
or perhaps if you only have MyCollectionViewCell
instances, this will work: 或者如果您只有MyCollectionViewCell
实例,这将有效:
for cell in cv.visibleCells() as [MyCollectionViewCell] {
// do something
}
Im using this code , to loop through all table view cells , even not visible ones , you can use it is applied to collection views for sure , 我使用这段代码,循环遍历所有表格视图单元格,甚至是不可见的单元格,你可以使用它来应用于集合视图肯定,
check my answer here : 在这里查看我的答案:
https://stackoverflow.com/a/32626614/2715840 https://stackoverflow.com/a/32626614/2715840
In Swift 5: 在Swift 5中:
There are five cells in section 0. Set each cells' backgroundcolor. 第0节中有五个单元格。设置每个单元格的背景颜色。
for row in 0..<collectionView.numberOfItems(inSection: 0){
let indexPath = NSIndexPath(row:row, section:0)
let cell:UICollectionViewCell = collectionView.cellForItem(at: indexPath as IndexPath) ?? cell
switch row {
case 0:
cell.backgroundColor = .red
case 1:
cell.backgroundColor = .green
case 2:
cell.backgroundColor = .blue
case 3:
cell.backgroundColor = .yellow
default:
cell.backgroundColor = .white
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.