我想在 TableView 单元格内创建 Collection View 以水平滚动元素。但是我遇到了如何正确填写我的收藏 View 的问题。我需要一种方法将 Collection View 与我的数据连接起来。
我如何获取并遍历 TableView 单元格以找到所需的 Collection View 并返回包含数据的单元格?
最佳答案
下面是一个通用示例,说明如何将数据传递到 TableView 单元格内的 Collection View 。还有这个link是有关此主题的 youtube 教程。
模型:
class ListOfParents: NSObject {
var parents:[Parent]?
}
class Parent: NSObject {
var children: [Child]?
static func fetchParents(_ completionHandler: @escaping (ListOfParents) -> ()) {
//fetch parents data
}
}
class Child: NSObject {
}
TableView 单元格:
class CustomTableViewController: UITableViewController {
var listOfParents: ListOfParents?
override func viewDidLoad() {
super.viewDidLoad()
Parent.fetchparents { (listOfParents) in
self.listOfParents = listOfParents
}
tableView.register(CustomParentCell.self, forCellReuseIdentifier: "tableCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let parentsCount = listOfParents?.parents?.count else {return 0}
return parentsCount
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomParentCell
cell.parent = listOfParents?.parents?[indexPath.item]
return cell
}
}
父单元格:
class CustomParentCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var parent: Parent? {
didSet {
// set child value here
}
}
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
return collectionView
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(CustomChildCell.self, forCellWithReuseIdentifier: "childCellID")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let childrenCount = parent?.children?.count else {return 0}
return childrenCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "childCellID", for: indexPath) as! CustomChildCell
cell.child = parent?.children?[indexPath.item]
return cell
}
}
子单元格:
class CustomChildCell: UICollectionViewCell {
var child: Child?
}
关于ios - TableView 单元格内的 Collection View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37242479/