我想在collectionView上应用一个pagnination,这样如果项目小于等于4,则collectionView会重新加载数据。 我试过但是结果不合适,所有单元格都是第一次加载,当滚动结束时,它会终止应用程序,因为我将单元格项目增加到1,所以它会终止应用程序。
如何第一次只加载4个单元格,然后滚动后重新加载剩余的单元格。
我的ViewController代码:
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;
}
答案 0 :(得分:0)
当您询问单元格时,在检查提供的索引是否有效之前,您将从数组中获取数据。该行应该在if语句中移动以保证安全。