iOS_图片相关

iOS 自定义多选相册

2017-03-21  本文已影响193人  叫我龙哥

自定义多选相册

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

写在前面

本代码只展示了iOS默认的相册内容,如果读者有其他想法的欢迎再本代码基础上修改。

获取系统默认的相册

-(PHFetchResult *)smartAlbums{
    
    if (_smartAlbums == nil) {
        _smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    }
    return _smartAlbums;
}

获取系统相册中的相片

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

- (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上

具体的演示效果就是这样
上一篇下一篇

猜你喜欢

热点阅读