Swift: Add more data to TableView on Scroll & Delete No Longer Needed Data from the TableView

89 Views Asked by At

I am using parse server.

I have # of social media posts with data that I add to the tableview. Everything loads correctly. However, I have a massive amount of posts (50).

I only want to limit the tableview to have a max of 10, which I successfully use via query.limit. However, I would like to load the next 10 on the tableView once the user scrolls passed the last 10 of the series.

Additionally, I would like to delete the previous 10 of the series because this will take up too much data on my user's phone.

1

There are 1 best solutions below

2
LulzCow On

I would recommend against deleting the current items in the UITableView, as that's an abnormal design pattern and is likely to confuse your users. UITableViews and UICollectionViews are designed to reuse cells in order to be performant.

Here's how I would handle pagination. This example uses a UICollecitonView, but you should be able to apply the same logic with your tableview

var skip = 0
var loading = false
var fullyLoaded = false
var posts = [Post]()

func queryPosts(){
    guard !self.fullyLoaded else{return}
    guard !self.loading else{return}
    self.loading = true
    let query = Post.query()
    query?.limit = 10
    query?.skip = self.skip
    query?.findObjectsInBackground(block:{
        (posts, error) in
        for post in posts{
            self.posts.append(item)
        }
        self.skip = self.posts.count
        if posts.count == 0{self.fullyLoaded = true}
        self.loading = false
        self.collectionView.reloadData()
    })
}

func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
    let cell = collectionView.dequeueReusableCell(indexPath: indexPath) as PostCell
    cell.loadPost(self.posts[indexPath.item])

        if self.posts.count == indexPath.item - 1{
            self.queryPosts()
        }

    return cell
}