嵌套CollectionView没有正确设置数据源或代理?

时间:2018-06-11 00:54:56

标签: ios swift uicollectionview uicollectionviewcell

我有一个像这样的collectionView设置:

class TagViewController: UIViewController,  UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, SNPostViewCellDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
        timeline.delegate = self
        UserService.posts(for: User.current,tagString: self.tagTitle!) { (postStuff) in
            let posts = postStuff.0
            self.postIds = postStuff.1
            self.posts = posts.sorted(by: {
                $0.timeStamp.compare($1.timeStamp) == .orderedAscending
            })
            self.timeline.dataSource = self
            self.collectionView.dataSource = self
            //self.timeline.collectionViewLayout.invalidateLayout()
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.collectionView {
            return posts.count
        } else if collectionView == self.timeline {
            let first = posts.first?.timeStamp
            let last = posts.last?.timeStamp
            let months = last?.months(from: first!) ?? 0
            print("no of months",months)

            if let diff = last?.months(from: first!), diff <= 5 {
                return months + 5-diff
            } else {
                return months + 1
            }
        } else {
            preconditionFailure("Unknown collection view!")
        }
    }
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.collectionView {
            let post = posts[indexPath.row]
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SNPostViewCell
            cell.isVideo = post.isVideo
            cell.delegate = self
            cell.notes.text = post.notes
            cell.thumbnailURL = URL(string: post.thumbnailURL)
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            cell.timeStampLabel.text = formatter.string(from: post.timeStamp)
            cell.mediaURL = URL(string: post.mediaURL)
            cell.notes.topAnchor.constraint(equalTo: cell.thumbnail.bottomAnchor,constant: 0.0).isActive = true
            return cell
        } else if collectionView == self.timeline {
            let index = indexPath.row
            print(index,"index")
            let calendar = Calendar.current
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MMM"
            let firstPost = posts.first?.timeStamp
            let month = calendar.date(byAdding: .month, value: index, to: firstPost!)
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SNMonthViewCell", for: indexPath) as! SNMonthViewCell
            cell.monthLabel.text = dateFormatter.string(from: month!)
            cell.monthLabel.textAlignment = .center
            return cell
        } else {
            preconditionFailure("Unknown collection view!")
        }
    }

正如你可以看到我的帖子加载后,我设置了我的时间轴collectionView的dataSource - 时间轴是我感兴趣的,因为这是包含嵌套的subcollectionView。基本上它是如何工作的每个SNMonthViewCell标记为一个月 - 例如Jan,然后在单元格内,嵌套的子集合包含每天jan的单元格。现在,要在月份单元格中设置此日期collectionView的委托/数据源,我会这样做:

func collectionView(_ collectionView: UICollectionView,
                             willDisplay cell: UICollectionViewCell,
                             forItemAt indexPath: IndexPath){
    if collectionView == self.timeline{
        guard let monthViewCell = cell as? SNMonthViewCell else  {
            return
        }
        let index = indexPath.item
        let firstPost = self.posts.first?.timeStamp
        let monthDate = Calendar.current.date(byAdding: .month, value: index, to: firstPost!)
        let monthInt = Calendar.current.component(.month, from: monthDate!)
        let yearInt = Calendar.current.component(.year, from: monthDate!)
        let postDates = dates(self.posts, withinMonth: monthInt, withinYear: yearInt)
        let dayDelegatesInstance = dayCellDelegates(firstDay: (monthDate?.startOfMonth())!, monthPosts:postDates)
        monthViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: dayDelegatesInstance)
    }
}

class dayCellDelegates: NSObject,UICollectionViewDataSource, UICollectionViewDelegate {
    let firstDay: Date
    let monthPosts: [Post]

    init(firstDay: Date, monthPosts: [Post]){
        self.firstDay = firstDay
        self.monthPosts = monthPosts
    }

    func collectionView(_ collectionView: UICollectionView,
                        numberOfItemsInSection section: Int) -> Int {
        print("how many cells?")
        let range = Calendar.current.range(of: .day, in: .month, for: self.firstDay)!
        return range.count
    }

    func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        print("looking for cell!")
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dayCell",
                                                      for: indexPath as IndexPath)
        let components: Set<Calendar.Component> = [.day]
        //let contained = self.postDates.reduce(false,{Calendar.current.dateComponents(components, from: $0).day == indexPath.item})
        let filtered = self.monthPosts.filter { (post) -> Bool in
            Calendar.current.dateComponents(components, from: post.timeStamp).day == indexPath.item
        }
        if filtered.isEmpty == true {
            cell.backgroundColor = UIColor(red:0.15, green:0.67, blue:0.93, alpha:1.0)
        }
        return cell
    }
}

你可以看到我使用我的外部类dayCellDelegates来设置这个subcollectionView的委托。现在在我之前提到的SNMonthViewCell中,我设置了数据源和委托,如下所示:

class SNMonthViewCell: UICollectionViewCell {

    @IBOutlet private weak var dayTicks: UICollectionView!

    @IBOutlet weak var monthLabel: UILabel!

    func setCollectionViewDataSourceDelegate
        <D: UICollectionViewDataSource & UICollectionViewDelegate>
        (dataSourceDelegate: D) {
        dayTicks.delegate = dataSourceDelegate
        dayTicks.dataSource = dataSourceDelegate
        dayTicks.reloadData()
    }
}

太棒了......但是,我的subcollectionView的委托方法永远不会被调用。我怎么知道?因为我在前两种方法中放入的那些第一个印刷语句从未被调用....

我的时间表是什么样的?

enter image description here

不知何故只有一个月的鞋子,没有一天的细胞被吸引。我认为主要是因为这些委托和数据源方法没有用于绘制它们。我在这做错了什么?

1 个答案:

答案 0 :(得分:2)

让我们看一下设置dataSource并委托给SNMonthViewCell单元格时发生的事情

func collectionView(_ collectionView: UICollectionView,
    willDisplay cell: UICollectionViewCell,
    forItemAt indexPath: IndexPath){
    if collectionView == self.timeline{
        ...
        let dayDelegatesInstance = dayCellDelegates(firstDay: (monthDate?.startOfMonth())!, monthPosts:postDates)
        monthViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: dayDelegatesInstance)
    }
}

您实例化dayCellDelegates对象,将其设置为您的单元格即可。 dayCellDelegates将在函数退出时释放。

简单您需要做什么,它保存对dayCellDelegates个对象的引用,因此不会取消分配它们。你可以用不同的方式,但我建议使用词典。

首先,您需要在TagViewController类中创建属性private var dataSources: [IndexPath : dayCellDelegates] = [:]。现在,当调用willDisplay方法时,您需要将dayCellDelegates对象保存到字典

func collectionView(_ collectionView: UICollectionView,
    willDisplay cell: UICollectionViewCell,
    forItemAt indexPath: IndexPath){
    if collectionView == self.timeline{
        guard let monthViewCell = cell as? SNMonthViewCell else  {
            return
        }
        let index = indexPath.item
        let firstPost = self.posts.first?.timeStamp
        let monthDate = Calendar.current.date(byAdding: .month, value: index, to: firstPost!)
        let monthInt = Calendar.current.component(.month, from: monthDate!)
        let yearInt = Calendar.current.component(.year, from: monthDate!)
        let postDates = dates(self.posts, withinMonth: monthInt, withinYear: yearInt)
        let dayDelegatesInstance = dayCellDelegates(firstDay: (monthDate?.startOfMonth())!, monthPosts:postDates)
        dataSources[indexPath] = dayDelegatesInstance
        monthViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: dayDelegatesInstance)
    }
}

但是,每次调用方法时,您都将重写您的委托。要解决此问题,您需要检查先前是否已保存dayCellDelegates

if let dayDelegatesInstance = dataSources[indexPath] {
    monthViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: dayDelegatesInstance)
} else {
    let dayDelegatesInstance = dayCellDelegates(firstDay: (monthDate?.startOfMonth())!, monthPosts:postDates)
        dataSources[indexPath] = dayDelegatesInstance
        monthViewCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: dayDelegatesInstance)
}
相关问题