iOS自定义多选相册

自定义多选相册

一个项目需要类似于安卓的多选相册,而iOS自带的Piker只能单选,所以就想到了自定义,自定义的过程是辛苦的,结果出来之后是高兴的。

 <!--more-->
写在前面
本代码只展示了iOS默认的相册内容,如果读者有其他想法的欢迎再本代码基础上修改。
获取系统默认的相册
1
2
3
4
5
6
7
-(PHFetchResult *)smartAlbums{
if (_smartAlbums == nil) {
_smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
}
return _smartAlbums;
}
获取系统相册中的相片

默认的照片排序是时间先后顺序,这里我也规定了按照文件创建的先后顺序来排序呢,为了避免同时引用过多的image导致内存暴增,这里使用的都是缩略图,而且只允许引用前20项。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
- (void)initPhotoData{
[self.photoArray removeAllObjects];
__weak typeof(self) weakSelf = self;
for (PHCollection * obj in self.smartAlbums) {
if ([obj isKindOfClass:[PHAssetCollection class]]) {
PHAssetCollection *collection = (PHAssetCollection *)obj;
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
PHFetchResult *fetchReuslt = [PHAsset fetchAssetsInAssetCollection:collection options:options];
NSLog(@"count - %ld",(unsigned long)fetchReuslt.count);
if (fetchReuslt.count == 0) {
continue;
}
NSInteger count = 20<fetchReuslt.count?20:fetchReuslt.count;
__block NSInteger _index = 0;
for (NSInteger i = 0 ;i<count;i++) {
PHAsset *asset = fetchReuslt[i];
//使用PHImageManager从PHAsset中请求图片
NSInteger index = _index;
MyImageManager *imageManager = [MyImageManager defaultManager];
[imageManager requestImageForAsset:asset targetSize:CGSizeMake(ItemWidth()*2-2, ItemHieght()*2-2) contentMode:PHImageContentModeAspectFill options:self.requestOption Index:index resultHandler:^(UIImage *result, NSDictionary *info, NSInteger index) {
NSInteger IDKey = [info[@"PHImageResultRequestIDKey"] integerValue];
NSLog(@"%@,%ld,%ld,%ld",result,(long)IDKey,index,IDKey-index);
[weakSelf.photoArray addObject:result];
}];
_index++;
}
}else{
NSLog(@"NO");
NSAssert1(NO, @"Fetch Collect Not PHCollection:%@", obj);
}
}
NSLog(@"initPhotoDataDone");
}
将获取到的缩略图展示到CollectionView上

具体的演示效果就是这样