首页 > 解决方案 > How to detect a UIScrollView has finished scrolling when animation is false?

问题描述

I have a collectionView called timeline that is scrolling programmatically on the second to last line here:

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
        }
    }

later.. I am attempting to detect that this has finished scrolling with

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if scrollView == timeline {
        print("Did finish")
    }
}

func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
    if scrollView == timeline {
        print("Did finish")
    }
}

Neither print statement fires once the scroll has completed. I think partially because animation = false. When I set that to true, it prints Did finish correctly - I think specifically scrollViewDidEndScrollingAnimation prints even though scrollViewDidEndDecelerating still does nothing because its being scrolled programatically.

How can I detect that this scroll has finished?

标签: iosswiftuiscrollviewuicollectionview

解决方案


I think because you compare the collectionView with the scrollView

if scrollView == timeline

which is false , BTW you can use

func scrollViewDidScroll(_ scrollView: UIScrollView)

If there is no animation then in the next line after

timeline.scrollToItem(at: monthCellIndexPath, at: .centeredHorizontally, animated: false)

run what you want as it's will occur serially where scrolling ended successfully , no need to set it inside scrollView's delegate methods whether it's called or not


推荐阅读