Skip to content

Instantly share code, notes, and snippets.

@ocadaruma
Created April 19, 2014 04:57
Show Gist options
  • Save ocadaruma/11074536 to your computer and use it in GitHub Desktop.
Save ocadaruma/11074536 to your computer and use it in GitHub Desktop.
UICollectionViewで非同期に画像を取得して表示 ref: http://qiita.com/ocadaruma/items/6bec7366b1a3c63d7467
#import <UIKit/UIKit.h>
@interface CustomCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicatorView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
#import "ViewController.h"
#import "CustomCell.h"
static NSString* const kCellIdentifier = @"cell";
@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic) NSCache* imageCache;
@property (nonatomic) NSOperationQueue* queue;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellWithReuseIdentifier:kCellIdentifier];
self.imageCache = [[NSCache alloc] init];
self.queue = [[NSOperationQueue alloc] init];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
cell.imageView.image = nil;
[cell.indicatorView stopAnimating];
UIImage* image = [self.imageCache objectForKey:indexPath];
if (image) {
cell.imageView.image = image;
} else {
[cell.indicatorView startAnimating];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"画像のURL"]];
[NSURLConnection sendAsynchronousRequest:request queue:self.queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
CustomCell* aCell = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
UIImage *aImage = [UIImage imageWithData:data];
[aCell.indicatorView stopAnimating];
[self.imageCache setObject:aImage forKey:indexPath];
[collectionView reloadItemsAtIndexPaths:@[indexPath]];
}];
}
return cell;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment