表视图中的集合视图错误:滑动时索引范围和单元格内容更改



我试图在tableview中显示collectionview,但我不断得到错误索引超出范围,当我滚动时,单元格的内容发生了变化。这个原因是什么?我试了很多方法,但都解决不了。

视图控制器

var featuresVM = [FeaturesModel]()

override func viewDidLoad() {
super.viewDidLoad()
setupUI()
configure()
}


func setupUI() {
tableView.register(CustomCell.self, forCellReuseIdentifier: CustomCell.identifier)
tableView.rowHeight = 200

featuresVM =   [

FeaturesModel(imageName: "images", titleModel: [
Features(title: "Name", overview: "4"),
Features(title: "Price", overview: "5"),
Features(title: "Count", overview: "6"),
Features(title: "Date", overview: "7")]),
FeaturesModel(imageName: "images", titleModel: [
Features(title: "Ürün Adı", overview: "19"),
Features(title: "Ürün Fiyatı", overview: "20"),
Features(title: "Ürün Fiyatı", overview: "21"),
Features(title: "Ürün Fiyatı", overview: "22"),
Features(title: "Ürün Fiyatı", overview: "23"),
Features(title: "Ürün Fiyatı", overview: "24"),
Features(title: "S.K.T", overview: "25")]),

//And more
]
}
}
extension ViewController : UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return featuresVM.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return featuresVM[section].imageName
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CustomCell.identifier, for: indexPath) as! CustomCell
cell.viewModel = featuresVM[indexPath.section].titleModel
return cell
}

}

CollectionView委托,数据源

extension CustomCell : UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.identifier, for: indexPath) as? CollectionViewCell else {
return UICollectionViewCell()
}
cell.titleView.text = viewModel[indexPath.row].title
cell.overView.text = viewModel[indexPath.row].overview
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: baseCollectionView.bounds.width / 2 , height: baseCollectionView.bounds.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}

}

我解决了这个问题,这个问题原因是collectionviewdatasource和delegate tableviewcell。我在viewcontroller collectionviewdelegate和datasource中定义了它并解决了

最新更新