ios UICollectionViewCell滚动时自动重载如何停止

时间:2014-04-26 11:17:48

标签: ios objective-c uicollectionview

在iOS for iPhone应用程序中,我必须创建一个网格,所以我使用UICollectionView。问题是当我向下滚动时,它会自动重复数据并产生更多时间。如何自动停止数据添加,并且只加载一次数据。 这是我的代码

in viewDidLoad :
 [self.collectionView registerClass:[CVCell class] forCellWithReuseIdentifier:@"cvCell"]; 

-(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];


}


// add Grid

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

        return [self.setFacebookimage count];
   }

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
   return [setFacebookimage count];


}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    // Setup cell identifier
    static NSString *cellIdentifier = @"cvCell";

    CVCell *cell = (CVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    // by nishant set Grid image
    if([[setFacebookimage objectAtIndex:indexPath.row] isEqualToString:@"img19.png" ]){
        cell.cellimageview.image=[UIImage imageNamed:@"img19.png"];
    }else{

        NSData *imageDatafacebookGrid = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: [setFacebookimage objectAtIndex:indexPath.row]]];
        // NSLog(@"%@",imageDatafacebook);
        cell.cellimageview.image=[UIImage imageWithData:imageDatafacebookGrid ];
    }


    return cell;

}
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // Adjust cell size for orientation
    if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
        return CGSizeMake(100.f, 100.f);
    }
    return CGSizeMake(150.f, 150.f);
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
       // NSLog(@"End >>>>> End ");
}

在我的facebook数组中,我有5个数据。如何解决这个问题

1 个答案:

答案 0 :(得分:1)

您可以在NSCache中保存图像。因此,每次滚动时它都不会刷新Cell,它可以提高滚动速度。使用NSCache,您可以检查图像是否可用。如果没有,您可以下载并保存在NSCache

声明NSCahe *imageCache;

然后在cellForItemAtIndexPath中尝试以下代码段:

if (cell.cellimageview.image == nil) {
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloadQueue, ^{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString: [setFacebookimage objectAtIndex:indexPath.row]]];
    UIImage *image = [UIImage imageWithData:data];
    [imageCache setObject:image forKey:[setFacebookimage objectAtIndex:indexPath.row]];

    dispatch_async(dispatch_get_main_queue(), ^{
        cell.cellimageview.image = image;
    });
});
}