Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NSInternalInconsistencyException error from collectionView in swift

Hi I have two different cell(it may be 6-7 in the future) I return them by some case in cellForItem method of collection view but I got this error(the cell returned from -collectionView:cellForItemAtIndexPath: does not have a reuseIdentifier – cells must be retrieved by calling)

Here is my codes.

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let idx = viewModel?.component?.firstIndex(where: { $0.type == .summary }) {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SummaryCollectionViewCell.identifier, for: indexPath) as? SummaryCollectionViewCell else { return UICollectionViewCell() }
        if let summaryData = viewModel?.component?[idx].dataModel as? SummaryData {
            let summaryViewModel = SummaryCollectionViewCellViewModel(summaryData: summaryData)
            cell.configure(with: summaryViewModel)
        }
    } else if let idx = viewModel?.component?.firstIndex(where: { $0.type == .merchant }) {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MerchantCollectionViewCell.identifier, for: indexPath) as? MerchantCollectionViewCell else { return UICollectionViewCell() }
        if let merchantData = viewModel?.component?[idx].dataModel as? MerchantData {
            let merchantViewModel = MerchantCollectionViewCellViewModel(merchantData: merchantData)
            cell.configure(with: merchantViewModel)
        }
    }
    
    return UICollectionViewCell()
}

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is legal to say

return UICollectionViewCell()

in order to quiet the compiler, but it is illegal to execute it. You are executing it, because neither wing of your condition is returning a cell.

You are saying let cell = in both wings, but then you just throw cell away! You never say return cell. You must dequeue a cell, configure it, and return it. Do not return some other cell; return the cell you dequeued and configured, namely cell.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading