使用无限垂直滚动单元格创建UICollectionView

时间:2014-06-29 09:10:23

标签: ios ios7 uicollectionview uicollectionviewcell infinite-scroll

下面的代码从我的集合视图中调用,打印出50个单元格,从计数0的标签开始计数到49.

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 50;
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor whiteColor];

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 40.0)];
    view.backgroundColor = [UIColor blueColor];

    NSInteger i = indexPath.row;
    NSString *string = [[NSNumber numberWithInteger:i] stringValue];

    UILabel *infoLabel = [ [UILabel alloc ] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 40.0) ];
    infoLabel.textAlignment =  NSTextAlignmentLeft;
    infoLabel.textColor = [UIColor whiteColor];
    infoLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:(12.0)];
    infoLabel.text = string;
    [view addSubview:infoLabel];

    [cell addSubview:view];



    return cell;
}

当我滚动时,如何点击数40(屏幕上可见40),那么我想再加载50个单元格并继续从50到99计数,依此类推?

1 个答案:

答案 0 :(得分:3)

设置这样的阈值

self.threshold = self.dataSource.count - 10;

然后在scrollViewDidScroll:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray * indexPaths = [self.collectionView indexPathsForVisibleItems];

    for (NSIndexPath * ip in indexPaths)
    {
        if (ip.row > self.threshold)
        {
            // load other 50 pages
            [self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
            [self.collectionView reloadData];

            // update the threshold
            self.threshold += 50;
        }
    }
}