我使用自定义UICollectionView与自定义UICollectionViewCell:
class SelectTimeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, SliderDelegate {
@IBOutlet weak var collectionViewSlider: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionViewSlider?.register(DayCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionViewSlider.dataSource = self
collectionViewSlider.delegate = self
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("*\(indexPath.row)")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! DayCollectionViewCell
cell.tag = indexPath.row
return cell
}
}
class DayCollectionViewCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
override init(frame: CGRect) {
super.init(frame: frame)
setupDayTimeline(width: frame.width, height: frame.height)
}
func setupDayTimeline(width: CGFloat, height: CGFloat) {
let appsCollectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 30, width: width, height: height - 30), collectionViewLayout: layout)
return collectionView
}()
addSubview(appsCollectionView)
appsCollectionView.delegate = self
appsCollectionView.dataSource = self
appsCollectionView.register(UINib(nibName: "TimeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "timecell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(self.tag)
return myArray[self.tag].count
}
}
但是当我滚动我的UICollectionView并进入控制台时: * 0 0 0 * 1 1 0 * 2
因此,对于最后一个单元格,来自DayCollectionViewCell的函数 numberOfItemsInSection 早于MyViewController调用 cellForItemAt 。我该如何解决这个问题?
答案 0 :(得分:1)
如果我理解正确,DayViewCollectionCell
包含另一个集合视图,其中单元格被设置为其集合视图的数据源&代表。由于在xib中配置了它,它会立即开始从集合视图中获取查询,然后才能设置标记。
我认为解决方案是不在xib中设置数据源,然后在设置单元格标记后在运行时设置它。或者,保持设置,并将didSet
处理程序添加到cell.tag
,在单元格的集合视图中调用reloadData()
。