如何快速在一个方向上自动滚动 UICollectionview?

Dha*_*iya 6 xcode ios uicollectionview swift swift3

午安

我需要向一个方向滚动 uicollection 视图单元格。

例如:-

我有 4 个数据值的数组 -> ["apple","pen","book","bottle"]。

我需要像这样滚动 Uicollectionview 单元格:

苹果 -> 笔 -> 书 -> 瓶子 -> 苹果 -> 笔 -> 书 -> 瓶子 -> 继续..

我使用此代码进行自动滚动,但在我的情况下,集合视图滚动如下:

苹果 -> 笔 -> 书 -> 瓶子 <-(滚动回第一个索引)苹果 -> 笔 -> 书 -> 瓶子

代码:

@objc func scrollAutomatically(_ timer1: Timer) {

      if let coll  = CV_Slider {
            for cell in coll.visibleCells {
                let indexPath: IndexPath? = coll.indexPath(for: cell)
                if ((indexPath?.row)!  < self.arr_img_Slide.count - 1){
                    let indexPath1: IndexPath?
                    indexPath1 = IndexPath.init(row: (indexPath?.row)! + 1, section: (indexPath?.section)!)

                    coll.scrollToItem(at: indexPath1!, at: .centeredHorizontally, animated: true)
                }
                else{
                    let indexPath1: IndexPath?
                    indexPath1 = IndexPath.init(row: 0, section: (indexPath?.section)!)
                    coll.scrollToItem(at: indexPath1!, at: .centeredHorizontally, animated: true)
                }

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢。

hab*_*s93 2

1)从 \xe2\x80\x98collectionView:numberOfItemsInSection:\xe2\x80\x99 返回一些非常大的数字,如 NSIntegerMax

\n\n

2) 在 \xe2\x80\x98collectionView:cellForItemAtIndexPath\xe2\x80\x99 中,而不是直接索引到数据源数组中以获取数据来填充单元格,使用 % 运算符。IE 执行以下操作:

\n\n
let item = datasource[indexPath.row % dataSource.count]\n
Run Code Online (Sandbox Code Playgroud)\n\n

代替:

\n\n
let item = datasource[indexPath.row]\n
Run Code Online (Sandbox Code Playgroud)\n\n

这将为您提供无限且循环的collectionView

\n