testALAssetsLibrary
- iOS開發(fā)中有時候會經(jīng)常需要拍照和選取圖片疾就,拍照直接調(diào)用UIImageViewPicker就可以了,如若要自定義相機(jī)的話可以自己定義拍照頁面做葵,此先略過不講坑鱼。這篇文章只講述如何自定義相冊——利用系統(tǒng)的<AssetsLibrary/AssetsLibrary.h>框架。
- 首先第一步呼股,當(dāng)然是要導(dǎo)入<AssetsLibrary/AssetsLibrary.h>框架
導(dǎo)入框架
#import <AssetsLibrary/AssetsLibrary.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
循環(huán)遍歷ALAssetsLibrary彭谁,調(diào)用enumerateGroupsWithTypes的block马靠。
[_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group)
{
//NSLog(@"*****相冊個數(shù)***%@",self.groupMutArr);
[self.groupMutArr addObject:group];
//每個相冊的名字
NSString *groupName = [group valueForProperty:ALAssetsGroupPropertyName];
[self.groupName addObject:groupName];
for (ALAssetsGroup *_group in self.groupMutArr)
{
[_group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result)
{
[self.imageArr addObject:result];
//NSLog(@"*****所有相冊里的所有圖片****%@",self.imageArr);
//UIImage *image = [UIImage imageWithCGImage: result.thumbnail];
//NSString *type=[result valueForProperty:ALAssetPropertyType];
}
}];
}
}
[self.collectionView reloadData];
} failureBlock:^(NSError *error) {
NSLog(@"獲取相冊失敗");
}];
根據(jù)數(shù)據(jù)數(shù)組來定義collectionView逞度,返回?cái)?shù)組
pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
NSMutableArray *testMutArr = [NSMutableArray array];
ALAssetsGroup *testGroup = [self.groupMutArr objectAtIndex:section];
[testGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result)
{
[testMutArr addObject:result];
}
}];
return testMutArr.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return self.groupMutArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
YBTNFirstCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:TNFirstCell forIndexPath:indexPath];
NSMutableArray *mutArr = [NSMutableArray array];
ALAssetsGroup *testGroup = [self.groupMutArr objectAtIndex:indexPath.section];
[testGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result){
[mutArr addObject:result];
}}];
ALAsset *result = [mutArr objectAtIndex:indexPath.item];
UIImage *image = [UIImage imageWithCGImage: result.thumbnail];
[cell setCellWithImage:image];
return cell;
}
項(xiàng)目截圖如下:

截圖
參考在此項(xiàng)目demo