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
}
>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
.