将代码从cellForItemAtIndexPath传输到CollectionViewCell(parsing后端)

我正在使用Parse作为我的应用程序的数据库。 我想创build一个CollectionViewCell并将其代码转移到那里,而不是在View Controller的cellForItemAtIndexPath中。 我该怎么做呢?

谢谢。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"productCell"; ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; PFObject *product = [self.products objectAtIndex:indexPath.row]; NSString *price = [NSString stringWithFormat:@"$%@.00", product[@"price"]]; cell.price.text = price; PFFile *userImageFile = product[@"firstThumbnailFile"]; [userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) { if (!error) { UIImage *thumbnailImage = [UIImage imageWithData:imageData]; UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage]; cell.image.image = thumbnailImageView.image; } }]; return cell; } 

Cell.h

 @interface ProductCell : UICollectionViewCell @property (nonatomic, weak) IBOutlet UIImageView *image; @property (nonatomic, weak) IBOutlet UILabel *price; @end 

请记住,单元格滚动到视图中时会cellForIndexPath调用cellForIndexPath 。 所以在这种方法中做非防备的networking请求是不好的做法。

如果您想要懒惰地获取图像,添加caching检索结果的逻辑,并且只能获取之前没有获取的图像…

 // in private interface @property(strong,nonatomic) NSMutableDictionary *imageForProduct; // in init self.imageForProduct = [@{} mutableCopy]; 

一种获取图像的方法…

 - (void)imageForProduct:(PFObject *)product completion:(void (^)(UIImage *))completion { PFFile *userImageFile = product[@"firstThumbnailFile"]; [userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) { UIImage *image; if (!error) { image = [UIImage imageWithData:imageData]; } completion(image); }]; } 

现在,在cellForIndexPath,我们不能指望图像到达时的集合状态是相同的,因此,而不是保留在完成块中操作单元格,只是重新加载索引path…

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"productCell"; ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; PFObject *product = [self.products objectAtIndex:indexPath.row]; NSString *price = [NSString stringWithFormat:@"$%@.00", product[@"price"]]; cell.price.text = price; if (self.imageForProduct[product.objectId]) { cell.image = self.imageForProduct[product.objectId]; } else { cell.image = // optionally put a placeholder image here [self imageForProduct:product completion:^(UIImage *)image { self.imageForProduct[product.objectId] = image; [collectionView reloadItemsAtIndexPaths:@[indexPath]]; }]; } return cell; } 

在您的.h文件中公开的自定义单元格中创build一个方法。

这个方法应该接收PFObjecttypes的参数。

然后在你cellForItemAtIndexPath,调用该方法,并在该方法传递你的对象。

在该方法的实现中,从对象中提取细节并将其分配给相应的属性。