I want create a Collection of images using UICollectionView
with auto scrolling(like loop).
Here is what i have done. Image Should Not be change.
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)
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…