在 CellForItemAt 之前调用 NumberOfItemsInSection

NumberOfItemsInSection is called before CellForItemAt

我将自定义 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 更早被调用。我该如何解决这个问题?

如果我理解正确,DayViewCollectionCell 包含另一个集合视图,其中单元格设置为其集合视图的数据源和委托。由于它是在 xib 中配置的,它会在您设置标签之前立即开始从集合视图中获取查询。

我觉得解决方法是在xib中不设置数据源,设置cell的tag后在运行时设置。或者,保持设置不变,然后将 didSet 处理程序添加到 cell.tag,您在单元格的集合视图中调用 reloadData()