本代码适用于iOS8,iOS9
#import "ViewController.h"
#import "ImageCell.h"
#import <Photos/Photos.h>
#import "UIView+Ext.h"
#define identifier @"image"
@interface ViewController () <UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *images;
@end
@implementation ViewController
- (NSMutableArray *)images {
if (_images == nil) {
_images = [NSMutableArray array];
}
return _images;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setupCollectionView];
[self fetchImages];
}
- (void)setupCollectionView {
[self.collectionView registerNib:[UINib nibWithNibName:@"ImageCell" bundle:nil] forCellWithReuseIdentifier:identifier];
NSInteger n = 4;
CGFloat margin = 1;
CGFloat width = (ScreenW - margin * (n + 1)) / n;
self.layout.itemSize = CGSizeMake(width, width);
self.layout.sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin);
}
- (void)fetchImages {
__weak typeof(self) weakSelf = self;
PHImageManager *manager = [[PHImageManager alloc] init];
PHFetchResult *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
[assetCollections enumerateObjectsUsingBlock:^(PHAssetCollection *assetCollection, NSUInteger idx, BOOL * _Nonnull stop) {
if ([assetCollection.localizedTitle isEqualToString:@"Camera Roll"]) {
weakSelf.title = assetCollection.localizedTitle;
PHFetchResult *assets = [PHAsset fetchKeyAssetsInAssetCollection:assetCollection options:nil];
[assets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL * _Nonnull stop) {
[manager requestImageForAsset:asset targetSize:self.layout.itemSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
[weakSelf.images addObject:result];
if (idx == assets.count - 1) {
[weakSelf.collectionView reloadData];
}
}];
}];
}
}];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.images.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.image = self.images[indexPath.row];
return cell;
}
@end