使用 scrollViewDidScroll 处理多个 Collection View Cells

Using scrollViewDidScroll to handle multiple Collection View Cells

我目前正在使用 scrollViewDidScroll 动画化我的 UICollectionView 单元格的偏移量。集合视图之前仅包含 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)")
    }
}

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

你可以试试

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

let detailCells  = mainCV.visibleCells.filter { [=11=] 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
        
    }

}