簡體   English   中英

在Swift中循環使用CollectionView單元格

[英]Looping through CollectionView Cells in Swift

我想知道如何遍歷當前可見的所有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

你正在使用它們的方式, as在該循環中試圖將可見單元格數組轉換為單個集合視圖單元格。 您想要轉換為數組:

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

或者如果您只有MyCollectionViewCell實例,這將有效:

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

我使用這段代碼,循環遍歷所有表格視圖單元格,甚至是不可見的單元格,你可以使用它來應用於集合視圖肯定,

在這里查看我的答案:

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

在Swift 5中:

第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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM