Problem encountered:
the cell returned from -collectionView:cellForItemAtIndexPath: does not have a reuseIdentifier - cells must be retrieved by calling - dequeueReusableCellWithReuseIdentifier:forIndexPath:"
In my TableViewCell, I have a CollectionViewCell.
import UIKit
protocol CollectionViewTableViewCellDelegate: AnyObject {
func collectionViewTableViewCellDidTapCell(_ cell: CollectionViewTableViewCell, viewModel: TitlePreviewViewModel)
}
class CollectionViewTableViewCell: UITableViewCell {
static let identifier = "CollectionViewTableViewCellId"
weak var delegate: CollectionViewTableViewCellDelegate?
private var titles: [Title] = [Title]()
private let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 140, height: 200)
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.register(TitleCollectionViewCell.self, forCellWithReuseIdentifier: TitleCollectionViewCell.identifier)
return collectionView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(collectionView)
collectionView.delegate = self
collectionView.dataSource = self
}
required init?(coder: NSCoder) {
fatalError()
}
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = contentView.bounds
}
public func configure(with titles: [Title]) {
self.titles = titles
DispatchQueue.main.async { [weak self] in
self?.collectionView.reloadData()
}
}
I extend this class CollectionViewTableViewCell as follows:
extension CollectionViewTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TitleCollectionViewCell.identifier, for: indexPath) as? TitleCollectionViewCell else {
return UICollectionViewCell()
}
//-- get the specific data from the pass-in Data
guard let model = titles[indexPath.row].poster_path else {
return UICollectionViewCell()
}
//- pass data to TitleCollectionViewCell
cell.configure(with: model)
return cell
}
In my Viewcontroller:
I have UItableView to retrieve the cell data as follows:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CollectionViewTableViewCell.identifier, for: indexPath) as? CollectionViewTableViewCell else {
return UITableViewCell()
}
cell.delegate = self
Base on the Problem: for UItableView,there is no such dequeue method: dequeueReusableCellWithReuseIdentifier.
How to solve this problem?
Thanks. Please kindly help me.