iOS 自定义多选相册

自定义多选相册

一个项目需要类似于安卓的多选相册,而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上

具体的演示效果就是这样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卟败灬筱龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值