【问题标题】:How to get current index path of collection view in swift如何快速获取集合视图的当前索引路径
【发布时间】:2019-12-17 09:22:15
【问题描述】:

我是 swift 的新手,我在获取当前集合视图的 indexpath 时遇到问题 我的代码是这样的

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    for cell in SliderCollectionView.visibleCells {
        let indexPath = SliderCollectionView.indexPath(for: cell)
        print(indexPath)
    }
}

我收到 indexPath 但像这样 Optional([0, 2]) 但我需要它作为 2

【问题讨论】:

  • 最正确的是收集它的项目而不是行
  • 这能回答你的问题吗? UICollectionView current visible cell index
  • @Sailendra 不,我接受了对我有帮助的答案
  • @Mujtaba 你的代码是正确的,只是你需要从 indexPath 中获取行,比如 print(indexPath.row)。

标签: ios swift uicollectionview


【解决方案1】:

你需要if-let

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    for cell in SliderCollectionView.visibleCells {
      if let row = SliderCollectionView.indexPath(for: cell)?.item {
           print(row) 
      }
    }
}

您可以直接访问可见索引

 for index in SliderCollectionView.indexPathsForVisibleItems {
    print(index.item)
 }

【讨论】:

    【解决方案2】:

    indexPath 更改为indexPath.row

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        for cell in SliderCollectionView.visibleCells {
            let indexPath = SliderCollectionView.indexPath(for: cell)
            print(indexPath.row)
    
        }
    }
    

    【讨论】:

      【解决方案3】:

      试试这个

      if let indexPath = collectionView.indexPath(for: cell) {
         print(indexPath.row)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-28
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 2022-10-17
        • 2010-10-26
        • 2011-09-22
        相关资源
        最近更新 更多