如何在Swift中使UICollectionview自动向一个方向滚动?

7

中午好

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

例如:

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

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

apple -> pen -> book -> bottle -> apple -> pen -> book -> bottle -> 继续...

我使用了这段代码来自动滚动,但是在我的情况下,集合视图会像这样滚动:

apple -> pen -> book -> bottle <- (向后滚动到第一个索引) apple -> pen -> book -> bottle

代码:

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

            }
        }
    }

提前感谢。


我认为你需要一个循环集合视图,这是链接 https://www.raywenderlich.com/1702-uicollectionview-custom-layout-tutorial-a-spinning-wheel - Chirag Shah
2个回答

2

1) 在“collectionView:numberOfItemsInSection:”中返回一些非常大的数字,比如NSIntegerMax。

2) 在“collectionView:cellForItemAtIndexPath”中,不要直接索引数据源数组来获取填充单元格的数据,而是使用%运算符。例如:

let item = datasource[indexPath.row % dataSource.count]

改为:

let item = datasource[indexPath.row]

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


1
如果您想只在右侧滚动,则可以像这样操作:
1)将第一个对象添加到最后
["apple","pen","book","bottle","apple"]

2) 现在,您已经实现了collectionView相关的delegate和dataSource方法,因此没有任何更改。

3) 现在,由于它正在自动滚动,当最后一个索引到达时,您应该无动画地滚动到第一个索引。

@objc func scrollAutomatically(_ timer1: Timer) {

        if let coll  = CV_Slider {
            for cell in coll.visibleCells {
                let indexPath: IndexPath? = coll.indexPath(for: cell)

                //0,1,2,3,4
                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)
                    if indexPath1.row == self.arr_img_Slide.count - 1 {
                        let indexPath2: IndexPath?
                        indexPath2 = IndexPath.init(row: 0, section: (indexPath?.section)!)
                        coll.scrollToItem(at: indexPath2!, at: .centeredHorizontally, animated: false)
                    }
                }
            }
        }
    }

尝试并分享你的结果。


好的,那么,什么不适当?您能否通过GIF或视频添加更多详细信息,以帮助您更好地了解所得到的结果。 - Bhavin Kansagara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接