从API中填充TableView中的CollectionView

我正在使用alamofire通过模型类的帮助从数组中获取数据。 现在我想在TableView中的CollectionView中显示这些数据。 所以传递数组来显示数据是一个问题,这里是一些代码,看看你是否能find问题。

告诉我,如果你想让我给你更多的信息

cellviewrowat的tableview

if let cell = tableView.dequeueReusableCell(withIdentifier: "HeadlineRow", for: indexPath) as? HeadlineRow { let latest = self.latest[indexPath.section] cell.updateUI(latest: latest) return cell } 

tableviewcell类

 var latestNews = [LatestNews]() func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HeadlineCell", for: indexPath) as? HeadlineCell { let latest = self.latestNews[indexPath.row] cell.updateUI(latest: latest) return cell } return UICollectionViewCell() } func updateUI(latest: LatestNews) { self.latestNews.append(latest) } 

集合视图类

 func updateUI(latest: LatestNews){ self.headlineImg.sd_setImage(with: URL(string: latest.thumbnail)) headlineTextView.text = latest.headline } 

所以问题基本上是我如何将数组从MainViewController转移到自定义的集合视图类的自定义TableView类。

UITableViewCell类:

 class MyTableViewCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout { var data : [SomeData]? @IBOutlet var collectionView: UICollectionView! // initialize your collectionview from storyboard func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellIdentifier", for: indexPath) as! MyCustomCollectionViewCell return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 100, height: 100) } func initCollection() { self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.register(UINib(nibName:"MyCustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "myCellIdentifier") } func setData(data: [SomeData]) { self.data = data self.initCollection() self.collectionView.reloadData() } } 

tableview的cellForRowAt:

 let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCellIdentifier", for: indexPath) as! MyTableViewCell cell.setData(data: yourArray) 

你也可以从cellForRowAt初始化“数据”数组,如:

 cell.data = yourArray 

这是我为我的项目包含水平collectionview在tableviewcell中的示例