Loading data into UICollectionView bunch by bunch

回眸只為那壹抹淺笑 提交于 2020-01-06 05:56:25

问题


I am building an chat app and I have a problem with the collection view. In my app I just want to do something like whatsapp, in starting I load the first 50 messages and when we scroll down then want to fetch other messages bunch by bunch. But when I doing this and call the collection view reloadData method then it scroll to the top message. And I don't want they scrolling. Can you help me. Please..

I just simply want to make the collectionView similar to whatsapp's chat view.. i.e. load more messages when user scroll to the older messages.


回答1:


What you are asking for is just feeding (inserting) cell into collection view without reloading it.

Check this appledoc, on inserting item.

determine the new indexPaths and then feed it to collection view using following

yourCollectionView.insertItems(at indexPaths: newIndexPaths)



回答2:


Detect when you reach at the end and fetch more data

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)
    {
    let lastSectionIndex = collectionView.numberOfSections - 1
    let lastRowIndex = collectionView.numberOfItems(inSection: lastSectionIndex) - 1
    if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex 
    {
        //fetch more items
        //add items to data array
        //Reload collectionview
    }
}



回答3:


Try pagination concept

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    if indexPath.row + 1 == dataArray.count && dataArray.count < completeData.count {
        fetchMoreData()
    }
    .....
}

func fetchMoreData() {

    //Fetch and add more data to your dataArray.
    //Reload collectionView
}


来源:https://stackoverflow.com/questions/52945515/loading-data-into-uicollectionview-bunch-by-bunch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!