【问题标题】:Looping through CollectionView Cells in Swift在 Swift 中循环遍历 CollectionView 单元格
【发布时间】:2014-08-25 16:31:30
【问题描述】:

我想知道如何遍历当前可见的所有 CollectionView 单元格。

在 Objective C 中,我将实现如下所示的这个概念:

for(UICollectionView *cell in collectionView.visibleCells){

}

我试过把它改成swift:

for cell:MyCollectionViewCell in self.collectionView.visibleCells() as cell:MyCollectionViewCell {

}

但是我收到以下错误:

Type 'MyCollectionViewCell' does not conform to protocol 'SequenceType'

如何循环遍历我的所有 CollectionViewCells

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell


    【解决方案1】:

    您在该循环中使用as 的方式是尝试将可见单元格数组转换为单个集合视图单元格。你想转换成一个数组:

    for cell in cv.visibleCells() as [UICollectionViewCell] {
        // do something        
    }
    

    或者如果您只有 MyCollectionViewCell 实例,这将起作用:

    for cell in cv.visibleCells() as [MyCollectionViewCell] {
        // do something 
    }
    

    【讨论】:

      【解决方案2】:

      在 Swift 5 中:

      section 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
                  }
              }
      

      【讨论】:

        【解决方案3】:

        我正在使用此代码,循环遍历所有表格视图单元格,即使是不可见的单元格,您也可以使用它来确定应用于集合视图,

        在这里查看我的答案:

        https://stackoverflow.com/a/32626614/2715840

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-10-15
          • 2021-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-04-16
          • 1970-01-01
          相关资源
          最近更新 更多