Search code examples
iosswiftuicollectionviewicarousel

how to convert a collection view to circular icarousel in swift


I want to show cells in collection view like in circular list, means that after the last cell of the collection view, on scrolling the collection view shows the first cell again, like circular linklist

I have tried using icrousel, but as icarosuel deals with views only, I don't want to finish the collection view completely and start again with icarousel, so is there any way I can make me collection view circular

this is my collectionView code

        func collectionView(_ collectionView: UICollectionView, 
         cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = 
                collectionView.dequeueReusableCell(withReuseIdentifier: 
                "CellName", for: indexPath as IndexPath) as! CellName

        let gigModel = self.datasoruce?[indexPath.row]

        cell.lblTitle.text = gigModel?.title

        cell.btnPrice.setTitle(gigModel?.getPriceAccordingToGigType(), 
         for: .normal)

          cell.itemImageView.sd_setImage(with: URL(string: 
          (gigModel?.getPhotoPath())!), placeholderImage: 
          UIImage.init(named: "place_holder"))

        cell.itemImageView.layer.cornerRadius = 10.0

        if Utilities.isValidString(object: gigModel?.adminId as 
         AnyObject) {
            cell.btnStar.isHidden = false
        }
        else {
            cell.btnStar.isHidden = true
        }

        return cell
         }

and I want this to be circular list.


Solution

  • I tried to create sample project and it was pretty simple, here is example code how you can implement "infinite" scroll

        class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
        var array: [Any] = [0,1,2,3,4,5,6,7,8,9]
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return Int(Int16.max) // Int.max cause crash
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCell
            let correctIndex = indexPath.row >= array.count ? indexPath.row % array.count : indexPath.row
            cell.nameLabel.text = "\(array[correctIndex])"
            return cell
        }
    
    }
    

    Hope it will help you