在 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如下
- (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屋!