问题
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