【问题标题】:How to auto scroll UICollectionview in one direction swift?如何快速向一个方向自动滚动 UICollectionview?
【发布时间】:2019-02-15 14:56:31
【问题描述】:

中午好

我需要向一个方向滚动 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)
                }

            }
        }
    }

提前致谢。

【问题讨论】:

标签: ios swift xcode swift3 uicollectionview


【解决方案1】:

如果你只想在右侧滚动,那么你可以这样做:

1) 将第一个对象添加到最后一个对象

["apple","pen","book","bottle","apple"]

2) 现在,由于您已经实现了与 collectionView 相关的委托、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 或视频中添加更多详细信息,以获得更好地帮助您的结果。
【解决方案2】:

1) 从‘collectionView:numberOfItemsInSection:’返回一些非常大的数字,比如 NSIntegerMax

2) 在“collectionView:cellForItemAtIndexPath”中,而不是直接索引到数据源数组以获取数据以填充单元格,使用 % 运算符。 IE。做:

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

代替:

let item = datasource[indexPath.row]

这会给你一个无限循环的collectionView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 2014-02-01
    • 1970-01-01
    相关资源
    最近更新 更多