我试图将集合视图嵌入自定义UITableViewCell中,该UITableViewCell用作每个表视图单元格的HeaderView。这是我在情节提要中使用的层次结构
这是“自定义标题表视图”单元格的代码。集合视图从情节提要板连接到类,在表视图单元格中设置委托和数据源,并实现CollectionView数据源中所需的所有协议。出于测试目的,我只是将项目数硬编码为十,并且该单元格应该只显示一个标签,文本为“ test”,背景色为红色
var headerDelegate:HeaderTableViewCellDelegate?
var timeInterval:TimeInterval?
@IBOutlet private weak var collectionView: UICollectionView!
var exercise:ExerciseRealm!
var workout:Workout!
@IBOutlet weak var collectionLayout: UICollectionViewFlowLayout! {
didSet {
collectionLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
@IBOutlet weak var exerciseNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.collectionView.delegate = self
self.collectionView.dataSource = self
//TODO: need to setup collection view flow layout
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.itemSize = CGSize(width: 70,height: 80)
flowLayout.minimumLinespacing = 5.0
flowLayout.minimumInteritemSpacing = 5.0
self.collectionView.collectionViewLayout = flowLayout
}
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
return 10
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewID",for: indexPath) as! HeaderCollectionViewCells
cell.updateCellWithIndicator(indicator: "test")
cell.backgroundColor = .red
return cell
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,insetforSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0,left: 10,bottom: 0,right: 10)
}
在我的主要TableViewController中,我使用以下代码将此单元格显示为标题视图
override func tableView(_ tableView: UITableView,viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
guard let workout = workout else {print("workout is nil in viewForHeaderInSection");return cell}
let exercises = workout.exercisesList
cell.headerDelegate = self
cell.exercise = exercises[section]
cell.workout = workout
return cell
}
尽管我已经设置了数据源,并从故事板和代码中将集合视图中的数据委托到自定义标题表视图单元中,但仍然没有显示集合视图。标头视图中的所有其他数据均按预期显示,因此我实在不知道实现集合视图时会丢失什么。