【发布时间】:2021-06-22 15:22:41
【问题描述】:
我知道这听起来很重复,并且像这样问了数百万个问题,但是当我在 iOS 14 上的 tableView 单元格中使用 collectionView 时,不会调用 collectionView cellForItemAt 函数,它适用于 iOS 12。
I attached a demo project for it.
这是我的 tableView 单元格,其中 i 内有一个 collectionView:
class ServicesTableViewCell: UITableViewCell {
@IBOutlet weak var parentView: UIView!
@IBOutlet weak var collectionView: UICollectionView!
var items = [String]()
var data: ServiceRow?
override func awakeFromNib() {
super.awakeFromNib()
collectionView.frame.size = CGSize(width: screenWidth, height: 50)
collectionView.register(UINib(nibName: "ServiceFilterCell", bundle: Bundle.main), forCellWithReuseIdentifier: "ServiceFilterCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.reloadData()
}
func fill(with data:ServiceRow) {
items = data.items?.compactMap({$0.name}) ?? []
parentView.backgroundColor = .clear
collectionView.reloadData()
}
}
extension ServicesTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // <= This guy is not called
let data = items[collectionView.tag]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ServiceFilterCell", for: indexPath) as! ServiceFilterCell
cell.fill(title: data, isSelected: false)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 80, height: 40)
}
}
这是我的父类 tableView cellForRowAt:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ServicesTableViewCell", for: indexPath) as! ServicesTableViewCell
cell.collectionView.tag = indexPath.section
cell.fill(with: services[indexPath.section])
cell.frame.size = CGSize(width: cell.frame.width, height: 50)
cell.collectionView.reloadData()
cell.layoutIfNeeded()
return cell
}
这是 Tarun Tyagi 答案的截图:
最后,问题是 tableViewCell 的 xib 文件在我创建时符合 collectionViewCell,所以我创建了一个 tableViewCell,现在一切正常!
【问题讨论】:
-
请提供具有非零宽度/高度的collectionView的源代码的更新链接。
-
@Tarun Tyagi,我更新了附件。我在 tableView 的底部添加了第二个 collectionView 以确保 collectionView 没有任何问题。
标签: swift uitableview uicollectionview