通过滚动到底部尝试加载表视图的新项目

时间:2017-10-13 17:20:25

标签: swift

我尝试在用户点击底部时向表格视图中添加新项目。

这是我试过的:

 /* Scrolling */

    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        let height = scrollView.frame.size.height
        let contentYoffset = scrollView.contentOffset.y
        let distanceFromBottom = scrollView.contentSize.height - contentYoffset
        if distanceFromBottom < height {
            self.viewModel.loadMoreCharacters()
        }
    }

LoadMoreCharacters func像这样开始:

func loadMoreCharacters(){

        guard isLoading.value == false else {
            print("Already try to load items")
            return
        }
        isLoading.value = true
        print ("start load")

 isLoading.value = true

        ApiManager.shared.getCharacters(offset: offset, limit: limit, orderBy: OrderBy.name) { [unowned self] (success, charIds) in

            if (success){
                self.addItemsWithNewCharactersIds(charIds: charIds ?? [])
                self.offset += 10
                 self.isLoading.value = false
                print("have new")
            }   else {
                self.isLoading.value = false
                self.delegate?.finishLoadingWithError(error: nil)
            }
        }

由于某种原因,该代码执行了2次。我希望它执行一次(我的意思是请求)。

1 个答案:

答案 0 :(得分:1)

我个人不会仅仅依赖于scrollViewDidScroll委托,因为其他可以滚动它的东西也可能不是来自用户交互。您可以尝试利用这两个代表来查看是否是滚动的用户

var userScrolling = false

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (userScrolling) {
        let height = scrollView.frame.size.height
        let contentYoffset = scrollView.contentOffset.y
        let distanceFromBottom = scrollView.contentSize.height - contentYoffset
        if distanceFromBottom < height {
            self.viewModel.loadMoreCharacters()
        }
    }
}

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    userScrolling = true
}

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    userScrolling = false
}
  

func scrollViewWillEndDragging(UIScrollView,withVelocity:CGPoint,   targetContentOffset:UnsafeMutablePointer)告诉委托   当用户完成滚动内容时。

     

func scrollViewWillBeginDragging(UIScrollView)告诉委托何时   滚动视图即将开始滚动内容。

它仅指定用户是在文档中scrollViewWillEndDragging触发滚动的用户,不确定scrollViewWillBeginDragging。但是我在xcode中尝试过,它对我有用。

编辑:您可能还需要查看scrollViewDidEndDeceleratingscrollViewWillBeginDecelerating,以防用户向底部轻扫并立即离开