如何在scrollViewDidScroll回调中使用滚动到单元格?

时间:2018-09-04 22:10:20

标签: ios swift uiscrollview uicollectionview

我具有以下功能,当显示单元格时,它将时间轴自动滚动到最后一个可能的单元格。

var onceOnly = false
internal func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if !onceOnly {
        let indexToScrollTo = IndexPath(row: self.posts.count - 1, section: 0)
        collectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
        let firstPost = posts.first?.timeStamp
        let firstOfFirstMonth = firstPost?.startOfMonth()
        let diff = posts.last?.timeStamp.months(from: firstOfFirstMonth!)
        //self.currentPostMonth = diff
        let monthCellIndexPath = IndexPath(row: diff!, section: 0)
        timeline.scrollToItem(at: monthCellIndexPath, at: .centeredHorizontally, animated: false)
        onceOnly = true
    }
} 

然后我想检测我的时间轴何时完成滚动,一旦完成,请在该单元格上调用特定方法(cell.drawArrow)

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == self.timeline {
        let months = self.posts.first?.timeStamp.startOfMonth().months(from: (self.posts.last?.timeStamp)!)
        let monthCellIndexPath = IndexPath(row: months!, section: 0)
        print("cells are",self.timeline.visibleCells)
        if let optionalCell = self.timeline.cellForItem(at: monthCellIndexPath) {
            let cell = optionalCell as! TimelineMonthViewCell
            let day = Calendar.current.component(.day, from: self.currentPostDate!)
            cell.drawArrow(day: day)
        } else {
            print("cell out of range")
        }
    }
}

现在它会打印“单元格为[]”和“单元格超出范围”。因此,它会找到可见单元格的空数组,而无法找到屏幕上显示范围内的最后一个单元格。我认为这可能意味着它试图在加载可见单元之前执行此操作?即使我认为应该在加载了回调之后调用那些考虑滚动到它们的人?

无论如何,我该怎么做?

1 个答案:

答案 0 :(得分:1)

事件的顺序是:

let indexToScrollTo = IndexPath(row: self.posts.count - 1, section: 0)
collectionView.scrollToItem(at: indexToScrollTo, at: .left, animated: false)
// callback
// more work to do

因此回调在完成您的工作之前到达。

没有动画,因此您不需要回调,无论如何这都是错误的回调。如果您还有更多工作要做,那就去做吧。