我想为图像创建一个 CollectionView 像循环一样自动滚动
Posted
技术标签:
【中文标题】我想为图像创建一个 CollectionView 像循环一样自动滚动【英文标题】:i want create a CollectionView for images with auto scrolling like loop 【发布时间】:2019-03-16 11:28:55 【问题描述】:我想使用 UICollectionView
自动滚动(如循环)创建图像集合。
这是我所做的。图片不应更改。
import UIKit
class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate
@IBOutlet weak var collectionView: UICollectionView!
var scrollingTimer = Timer()
var dataArray: [String] = ["image0","image1","image2"]
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return dataArray.count
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCollectionViewCell
cell.img.image = UIImage(named: dataArray[indexPath.row])
var rowIndex = indexPath.row
let numberOfRecords : Int = self.dataArray.count - 1
if(rowIndex < numberOfRecords)
rowIndex = (rowIndex + 1)
else
rowIndex = 0
scrollingTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.startTimer(theTimer:)), userInfo: rowIndex, repeats: true)
return cell
@objc func startTimer(theTimer : Timer)
UIView.animate(withDuration: 1.0, delay: 0, options: .curveLinear, animations:
self.collectionView.scrollToItem(at: IndexPath(row: theTimer.userInfo! as! Int , section:0), at: .centeredHorizontally, animated: false)
, completion: nil)
【问题讨论】:
github.com/nicklockwood/iCarousel 【参考方案1】:使用此代码。希望对您有所帮助。
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(moveToNextPage), userInfo: nil, repeats: true)
@objc func moveToNextPage ()
if self.x < dataArray.count
let indexPath = IndexPath(item: x, section: 0)
sliderPageCont.currentPage=x
sliderColletion.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
self.x = self.x + 1
else
self.x = 0
【讨论】:
以上是关于我想为图像创建一个 CollectionView 像循环一样自动滚动的主要内容,如果未能解决你的问题,请参考以下文章
如何为自定义 TableViewCell 和 CollectionView Cell 使用一个 UIView。?