【问题标题】:Using scrollViewDidScroll to handle multiple Collection View Cells使用 scrollViewDidScroll 处理多个 Collection View Cells
【发布时间】:2021-03-15 23:05:43
【问题描述】:

我目前正在使用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?

【问题讨论】:

    标签: swift uicollectionview uiscrollview uicollectionviewcell


    【解决方案1】:

    你可以试试

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多