Home > database >  UICollectionView displays empty and doesn't show any cells
UICollectionView displays empty and doesn't show any cells

Time:10-25

I am just testing the code to see if it can load the collection view. But id doesn't show anything. Please look at the code below and let me know where I am wrong.

import UIKit
    

private let reuseIdentifier = "Cell"
class FeedController: UICollectionViewController {

   
    //MARK: - Lifecycle
    override func viewDidLoad() {
    super.viewDidLoad()
    configureUI()
    collectionView.dataSource = self
    collectionView.delegate = self
        self.collectionView.reloadData()
    }
    
    
    //MARK: - Helpers
    
    func configureUI() {
        collectionView.backgroundColor = .white
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
       
    }
}
//MARK:- UICollectionViewDataSource

extension FeedController {
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
        cell.backgroundColor = .systemRed
        return cell
    }
}

extension FeedController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 200)
    }
}

CodePudding user response:

Set a breakpoint somewhere in viewDidLoad to test if it even calls any code of this class when running the app.

Normally you get an error when you set the dataSource and delegate in a UICollectionViewController, because these are already set by the controller. Because of this, move the extension lines to the main class and remove the extension.

CodePudding user response:

You need to initialize FeedController using public init(collectionViewLayout layout: UICollectionViewLayout) UICollectionViewController initializer, else you have no layout assigned to the UICollectionView.

Wherever you are doing FeedController() you should do FeedController(collectionViewLayout: UICollectionViewFlowLayout()) or some custom UICollectionViewLayout.

  • Related