使用 scrollViewDidScroll 处理多个 Collection View Cell

问题描述

我目前正在使用 UICollectionView 为我的 scrollViewDidScroll 单元格的偏移设置动画。集合视图以前只包含 1 个 UICollectionViewCell

我刚刚在同一个集合视图中添加了另一个 UICollectionViewCell,并且想要执行相同的动画。问题是,我因错误而崩溃:

Precondition Failed: NSArray element Failed to match the Swift Array Element type. Expected DetailedCell but found BasicCell

我的进步:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    // First (Detailed Cell)
    for newDetailedCell in mainCV.visibleCells as! [DetailedCell] { // Crashes on this line
        let indexPath = mainCV.indexPath(for: newDetailedCell)
        print("indexPath for Detailed Cell: \(indexPath)")
    }

    // Rest (Basic Cell)
    for basic in mainCV.visibleCells as! [BasicCell] {
        let indexPath = mainCV.indexPath(for: basic)
        print("indexPath for Basic Cell: \(indexPath)")
    }
}

如何使用两个不同的 CollectionViewCell 访问visibleCells?

解决方法

你可以试试

for cell in mainCV.visibleCells {
   if let res = cell as? DetailedCell {
     //
   }
   else 
   if let res = cell as? BasicCell {
     //
   }
}  

let detailCells  = mainCV.visibleCells.filter { $0 is DetailedCell }  
for newDetailedCell in detailCells as! [DetailedCell] {  
    let indexPath = mainCV.indexPath(for: newDetailedCell)
    print("indexPath for Detailed Cell: \(indexPath)")
}
,

要处理多个 UICollectionView 的滚动事件,请在 scrollViewDidScroll 内实现此条件:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    if scrollView == collectionView1 {
    
        // Your code goes here
        
    }

    if scrollView == collectionView2 {
    
        // Your code goes here
        
    }

}