Search code examples
iosswiftuicollectionviewviewcontroller

Multiple CollectionViews in one ViewController


I try to show multiple collection views in one ViewController, but I get crash with error:

Thread 1: Exception: "could not dequeue a view of kind: UICollectionElementKindCell with identifier MainCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard"

I registered all the cells in Storyboard and this is my code for ViewController:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout  {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var horizontalNumbers: UICollectionView!
    @IBOutlet weak var verticalNumbers: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.delegate = self
        collectionView.dataSource = self

        horizontalNumbers.delegate = self
        horizontalNumbers.dataSource = self

        verticalNumbers.delegate = self
        verticalNumbers.dataSource = self
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        if collectionView == collectionView {
           return 81
        } else {
           return 9
        }
    }

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

        if collectionView == collectionView {
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainCell", for: indexPath) as! CollectionViewCell
           cell.backgroundColor = .systemGreen
           return cell
        } else if collectionView == horizontalNumbers {
           let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Horizontal", for: indexPath) as! HorizontalNumbersCell
           return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Vertical", for: indexPath) as! VerticalNumbersCell
            return cell
        }
    }
 
}

I checked everything twice and looked for some examples of code, but don't release why I get crash.


Solution

  • You need to register cell for all three collectionView.Take the collectionView for example.

    try

    collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MainCell") // if it is loaded in nib, and nib name is CollectionViewCell
    

    or

    collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "MainCell") // if it is written just in code
    

    in the viewDidLoad.

    Do the same thing for the horizontalNumbers, etc.

    Check https://developer.apple.com/documentation/uikit/uicollectionview/1618089-register for more details.