Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

ios - i want create a CollectionView for images with auto scrolling like loop

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use this code. I hope this helps you.

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

        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...