将其添加到 .h/.m 文件中
#import <Photos/Photos.h>
全局变量:
@property(nonatomic , strong) PHFetchResult *assetsFetchResults;
@property(nonatomic , strong) PHCachingImageManager *imageManager;
viewDidLoad代码:
// Fetch all assets, sorted by date created.
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
_assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
_imageManager = [[PHCachingImageManager alloc] init];
numberOfItemsInSection 方法:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [_assetsFetchResults count];
}
UICollectionView cellForItemAtIndexPath:代码:
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellID" forIndexPath:indexPath];
UIImageView *imageView = (UIImageView *)[cell viewWithTag:101];
PHAsset *asset = _assetsFetchResults[indexPath.item];
[_imageManager requestImageForAsset:asset targetSize:imageView.frame.size contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *result, NSDictionary *info)
{
imageView.image = result;
}];
[EDITED]
访问图像:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
PHAsset *asset = _assetsFetchResults[indexPath.item];
[_imageManager requestImageForAsset:asset targetSize:CGSizeMake(200, 200) contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *result, NSDictionary *info)
{
// result is the actual image object.
}];
}