Search code examples
swiftuicollectionviewuiscrollviewuicollectionviewcell

Using scrollViewDidScroll to handle multiple Collection View Cells


I am currently animating the offset of my UICollectionView cells with scrollViewDidScroll. The Collection View previously just contained 1 UICollectionViewCell.

I just added another UICollectionViewCell to the same Collection View, and would like to perform the same animation. The problem is, I am getting a crash with error:

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

My progress:

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)")
    }
}

How can I access visibleCells with two differet CollectionViewCells?


Solution

  • You can try

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

    OR

    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)")
    }