我想使用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)
}
答案 0 :(得分:-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
}
}