如何快速获取集合视图的当前索引路径

时间:2019-12-17 09:22:15

标签: ios swift uicollectionview

我是新手,我正面临获取当前收藏集视图indexpath的问题 我的代码是这样的

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

我得到indexPath,但是像这样Optional([0,2]) 但我需要2

3 个答案:

答案 0 :(得分:0)

您需要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)
 }

答案 1 :(得分:0)

尝试一下

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

答案 2 :(得分:0)

indexPath更改为indexPath.row

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

    }
}
相关问题