Swift UICollectionView 单元格被渲染两次

Swift UICollectionView Cell being rendered twice

我正在写一个客户日历作为我练习的挑战 UICollectionView。这个问题困扰了我几天。那么问题就出在它复用cell的时候,加载数据源函数已经被调用了两三次,那么就导致了:

有时会调用 3 次,我的日历天数会变成 100 110 等等

这是委托和数据源代码:

extension CalendarViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.calendarPages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CalendarCell
        cell.calendarPage = self.calendarPages[self.currentPageIndex]
        
        cell.contentView.addSubview(self.buildCalendarPage(index: indexPath.row, frame: cell.contentView.frame)) // this is where it add new month page to the calendar, and it's randomly called multiple times 
  
        print("cell called")
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
    }
}

我知道那里发生了什么,所以基本上我把它弄得太复杂了,在另一个 UICollectionView 中有一个日历 UICollectionView,(我只是想让它可以滚动),所以每次重复使用单元格时,我都忘记重新加载 UI

解决方法,只保留一个UICollectionView,每个cell是一天,再创建一个UICollectionViewCell class来控制可重用的cell,感谢Babar的帮助