我想在表格视图单元格内创建集合视图,以便水平滚动元素。但我有问题如何填写我的集合视图。我需要一种方法来将集合视图与我的数据连接起来。
如何获取并循环查看表视图单元格以查找所需的集合视图并返回包含数据的单元格?
答案 0 :(得分:0)
是如何将数据传递到表视图单元格内的集合视图的一般示例。此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?
}