简体   繁体   中英

How can i load multiple custom views in collection view swift

I have two collection view cells A and B , i need to load these cells simultaneously. But i didn't found any solutions

         firstCollectionView.register(UINib(nibName: "A", bundle:  Bundle.main), forCellWithReuseIdentifier: "A")
     firstCollectionView.register(UINib(nibName: "B", bundle:  Bundle.main), forCellWithReuseIdentifier: "B")

These are the two views and how can load 2 views at time.

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "A", for:indexPath) as? A

How do you want to divide the different cells type? with number? Like, if raw = 0,2,4,6 etc you will have firstCell and if raw = 1,3,5 etc you will have secendCell?

So maybe with something like this :

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = UICollectionViewCell()

        cell = collectionView.register(UINib(nibName: "B", bundle:  Bundle.main), forCellWithReuseIdentifier: "B")

        if indexPath.row % 2 == 0 {
            cell = collectionView..register(UINib(nibName: "A", bundle:  Bundle.main), forCellWithReuseIdentifier: "A")
        }

        return cell
    }

Register CustomCollectionViewCell in the viewDidLoad:

    var nib1 = UINib(nibName: "CustomCollectionViewCell1", bundle: nil)
    self.firstCollectionView().registerNib(nib1, forCellReuseIdentifier: "CustomCell1")
    var nib2 = UINib(nibName: "CustomCollectionViewCell2", bundle: nil)
    self.firstCollectionView().registerNib(nib2, forCellReuseIdentifier: "CustomCell2")

Now return your cell here cellForItemAtIndexPath: method,

//As per your condition check cell index or section or any other your condition.


 if indexPath.row % 2 == 0 {  

      // Create an instance of CustomCollectionViewCell1
     var cell: CustomCollectionViewCell1? = tableView.dequeueReusableCell(withIdentifier: "CustomCell1")
        if self.cell == nil {
            self.cell = CustomCollectionViewCell1(style: .subtitle, reuseIdentifier: "CustomCell1")
        }
     return cell!

    }else{
      // Create an instance of CustomCollectionViewCell2
     var cell: CustomCollectionViewCell2? = tableView.dequeueReusableCell(withIdentifier: "CustomCell2")
        if self.cell == nil {
            self.cell = CustomCollectionViewCell2(style: .subtitle, reuseIdentifier: "CustomCell2")
        }
     return cell!
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM