Created
April 19, 2014 04:57
-
-
Save ocadaruma/11074536 to your computer and use it in GitHub Desktop.
UICollectionViewで非同期に画像を取得して表示 ref: http://qiita.com/ocadaruma/items/6bec7366b1a3c63d7467
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface CustomCell : UICollectionViewCell | |
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicatorView; | |
@property (weak, nonatomic) IBOutlet UIImageView *imageView; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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