我正在使用 alamofire 在模型类的帮助下从数组内的 API 存储中获取数据。现在我想在 TableView 内的 CollectionView 中显示这些数据。因此,传递该数组以显示数据是一个问题,这里有一些代码,看看您是否能找到问题。
告诉我你是否想让我给你更多的信息
表格视图的单元格
if let cell = tableView.dequeueReusableCell(withIdentifier: "HeadlineRow", for: indexPath) as? HeadlineRow {
let latest = self.latest[indexPath.section]
cell.updateUI(latest: latest)
return cell
}
表视图单元类
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
这是我为我的项目完成的示例,其中包含 tableviewcell 中的水平集合视图
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句