集合视图分页 IOS



我想对集合视图应用分页,这样如果项目小于 4,集合视图将重新加载数据。我试过了,但结果不合适,所有单元格都是第一次加载的,滚动结束时,它会终止应用程序,因为我将单元格项目增加到 1,因此它会终止应用程序。

如何第一次只加载 4 个单元格,然后在滚动后重新加载剩余的单元格。

我的视图控制器代码:

NSInteger _currentPage;
@property (nonatomic, retain) NSMutableArray *items;

我的代码:

#define ITEMS_PAGE_SIZE 4
#define ITEM_CELL_IDENTIFIER @"Cell"
#define LOADING_CELL_IDENTIFIER @"LoadingItemCell"
- (void)viewWillAppear:(BOOL) animated
{
 UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
    collectionViewLayout.sectionInset = UIEdgeInsetsMake(20, 0, 20, 0);
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return arr.count+1;
}
    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        Data* d = arr[indexPath.row];
           if (indexPath.item < arr.count) {
               UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ITEM_CELL_IDENTIFIER forIndexPath:indexPath];
               UILabel *label = (UILabel *)[cell viewWithTag:200];
               label.text = [NSString stringWithFormat:@"%@",d.detail];
               return cell;
        } else {
            NSLog(@"FETCHING MORE ITEMS ******************");
            // Generate the 'next page' of data.
            NSMutableArray *newData = [NSMutableArray array];
            NSInteger pageSize = ITEMS_PAGE_SIZE;
            for (int i = _currentPage * pageSize; i < ((_currentPage * pageSize) + pageSize); i++) {
                [newData addObject:[NSString stringWithFormat:@"Item #%d", i]];
            }
            _currentPage++;

            // Simulate an async load...
            double delayInSeconds = 3;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // Add the new data to our local collection of data.
                for (int i = 0; i < newData.count; i++) {
                    [self.items addObject:newData[i]];
                }
                // Tell the collectionView to reload.
                [self.collectionView reloadData];
            });
        }
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:LOADING_CELL_IDENTIFIER forIndexPath:indexPath];
        UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]
                                                      initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        activityIndicator.center = cell.center;
        [cell addSubview:activityIndicator];
        [activityIndicator startAnimating];
        return cell;
    }

当被要求输入单元格时,您将在检查提供的索引是否有效之前将数据从数组中取出。为了安全起见,此行应移动到 if 语句内。

最新更新