【问题标题】:scrollViewDidLoad called multiple time while implementing infinite scroll实现无限滚动时多次调用scrollViewDidLoad
【发布时间】:2016-10-13 21:21:53
【问题描述】:

我试图在具有自定义布局的集合视图上实现无限滚动。

搜索后发现了这个方法:

    override func scrollViewDidScroll(_ scrollView: UIScrollView) {

    //make sure collection view is on screen
    if collectionView?.window == nil { return }

    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height

    if offsetY > contentHeight - scrollView.frame.size.height {
        print("scroll ended")
        getNextTenProducts()
        collectionView?.reloadData()
    }

}

然而,打印语句被多次调用,导致大量单元格被插入到集合视图中,有时它甚至被连续调用 20 次。

有解决办法吗?

【问题讨论】:

    标签: swift uiscrollview uicollectionview uiscrollviewdelegate


    【解决方案1】:

    我找到了解决方案:

        override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
        if collectionView?.window == nil { return }
    
        let offsetTolerance = CGFloat(30)
    
        let offsetY = scrollView.contentOffset.y
        let contentHeight = scrollView.contentSize.height
    
        if offsetY > contentHeight - scrollView.frame.size.height + offsetTolerance, !scrollViewReachedBottom {
            print("scroll ended")
            scrollViewReachedBottom = true
        } else if offsetY < contentHeight - scrollView.frame.size.height - offsetTolerance {
            scrollViewReachedBottom = false
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多