在CollectionView上的Scroll Demand上加载更多数据 [英] Load More data on Scroll Demand on CollectionView
问题描述
我正在实现collectionView上的功能,其中用户在底部滚动collectionView(20个项目),并从服务器请求另一组数据(另外20个项目).
I am implementing a feature on the collectionView where user scrolls the collectionView at the bottom (20 items) and it requests another set of data (20 more items) from the server.
我已经实现了以下两种方法.但是我想知道哪种方法更好吗?还是还有其他我不知道的更好的方法?
I have implemented the following two approaches. But I wonder which approach is better? or is there any other better approach which I am not aware of?
第一种方法是如下使用cellForItemAtIndexPath
中的indexPath
The first approach is to use the indexPath
in the cellForItemAtIndexPath
as follows
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
if(collectionView == productCollectionView)
{
__weak ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
// load more data
if(indexPath.row == numberOfItemsPerSection-1)
{
numberOfItemsPerSection += 20;
offset += 20;
[self loadFromURL];
}
// loading image and text happening here.
// it is not included here
return cell;
}
}
第二种方法是如下所述 scrollViewDidScroll
The second approach is to scrollViewDidScroll as follows
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height && pElements.count == numberOfItemsPerSection) {
numberOfItemsPerSection += 20;
offset += 20;
[self loadFromURL];
}
}
推荐答案
我通过CollectionViewDelegate方法执行此操作,例如:
I do this thing through CollectionViewDelegate method like:
- (void)collectionView:(UICollectionView *)collectionView
willDisplayCell:(UICollectionViewCell *)cell
forItemAtIndexPath:(NSIndexPath *)indexPath{
if indexPath.row == numberOfitem.count-1 && !self.waiting {
waiting = true;
self.loadMoreData()
}
}
-(void)loadMoreData(){
// After getting the response then
[numberOfitem addObjects : your response in term of array];
waiting = false;
}
在Swift 4.0中
In swift 4.0
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Note: ‘isWating’ is used for checking the paging status Is currency process or not.
if indexPath.section == self.dataSoruce.list.count - 2 && !isWating {
isWating = true
self.pageNumber += 1
self.doPaging()
}
}
private func doPaging() {
// call the API in this block and after getting the response
self.dataSoruce.append(newData);
self.tableView.reloadData()
self.isWating = false // it means paging is done and the user can able request another page request via scrolling the table view at the bottom.
}
这篇关于在CollectionView上的Scroll Demand上加载更多数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!