jamesCode
jamesCode

Reputation: 1

Infinite scroll tableView, swift

With some research I found this method quiete usefull to reach my purpose: pagination in a table view.

What I do is:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height
    
    if offsetY > contentHeight - scrollView.frame.height {

        //print

        if vievModel.!paginationFinished {
            self.viewModel.loadMoreData()
            self.tableView.reloadData()
        }
    }
}

The variable paginationFinished is manage in my viewModel, and when I call load more Data the page number is increasde by 1.

The problem is that this piece of code, when I scroll down to load more data, calls my viewModel function like all the possible times.

In fact if I print something in the line of my code it's printed like 15 times when i reach the end of my page.

What is the problem with this code? How can I improve this? I would like to reach the end of the page and call my loadMoreData once, so it loads the data in the pageCounter. I think i'm missing something

Upvotes: 0

Views: 2021

Answers (2)

Shashank Mishra
Shashank Mishra

Reputation: 1079

Add completion handler in loadMoreData() method & use a boolean check for call like below -

var isLoadingStarted = true

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height
    
    if offsetY > contentHeight - scrollView.frame.height {
        
        if vievModel.!paginationFinished && isLoadingStarted {
            isLoadingStarted = false
            self.viewModel.loadMoreData {
               self.tableView.reloadData()
               //self.isLoadingStarted = true
            }
            
        }
    }
}

//Handle loadMoreData method as below
static func loadMoreData(_ , completion:@escaping (() -> Void)) {
    .
    .
    .
    completion()
   
}

Use scroll view delegate to detect begin dragging and set flag isLoadingStarted there -

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    self.isLoadingStarted = true
}

Try it once.

Upvotes: 2

aiwiguna
aiwiguna

Reputation: 2922

you need to do some flagging

var isLoading = false

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    let contentHeight = scrollView.contentSize.height
    
    if offsetY > contentHeight - scrollView.frame.height && !isLoading {

        //print

        if vievModel.!paginationFinished {
            isLoading = true
            self.viewModel.loadMoreData()
            self.tableView.reloadData()
            isLoading = false
        }
    }
}

Upvotes: 1

Related Questions