iOS 图片选择器 多选 解读ElC敲了一遍 做成自己的组件,记录下

来源:互联网 发布:网络名誉侵权案例 编辑:程序博客网 时间:2024/05/21 22:58

图片选择器,开发iOS 必备的组件之一,也是常用的功能。所以自己整合了下ELC的组件把它变为自己的东西。 于之前自己做的Andoird图片选择器思路差不多,个人感觉iOS更加简单,没有所谓的自己读取数据,而Android 需要读取sqlite3的数据库,获取对应的字段才能得到图片的url实现自己需要的图片选择器。


实现思路:

1. 首先根据AlAssetsLibrary得到相册组,Gorup   传入所需要的block; 关键代码如下

//通过ALAssetsLibrary迭代取出所有相册[self.library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock:assetGroupEnumberatorFailure];

2.点击进入相册。点击的过程把相册作为参数设置到图片选择Controller中

//设置点击之后恢复到点击之前的效果[tableView deselectRowAtIndexPath:indexPath animated:YES];    SJImagePickerController *picker = [[SJImagePickerController alloc] init];picker.assetGroup = [self.assetGroups objectAtIndex:indexPath.row];[picker.assetGroup setAssetsFilter:[ALAssetsFilter allPhotos]];[self.navigationController pushViewController: picker animated:YES ];


3.在Controller拿到对应的Group 循环出所有的图片。

[self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index,BOOL *stop){        if (result == nil) {            return;        }                SJAsset *sjAsset = [[SJAsset alloc] init];        [sjAsset setAsset:result];               //所有图片集合       [self.sjAssets addObject:sjAsset];            }];

以上步骤通过AlAssetsLibrary类库获取图片信息的关键点;以下就是根据数据显示图片即可。


4.1 所需要的对象Cell对象

////  SJAssetCell.h//  HappyApp////  Created by LiShijia on 15/1/9.//  Copyright (c) 2015年 com.johnli. All rights reserved.//#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>#import "SJAsset.h"@interface SJAssetCell : UITableViewCell//data 数据 每一行的数据集 以及初始化 图片以及北京图片- (void)setAssets:(NSArray *)assets;//选择器图片行数@property (nonatomic, strong) NSArray *rowAssets;//每一行图片个数@property (nonatomic, strong) NSMutableArray *imageViewArray;//图片选中背景@property (nonatomic, strong) NSMutableArray *overlayViewArray;@end

////  SJAssetCell.m//  HappyApp////  Created by LiShijia on 15/1/9.//  Copyright (c) 2015年 com.johnli. All rights reserved.//#import "SJAssetCell.h"@implementation SJAssetCell//Using auto synthesizers- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];    if (self) {        UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellTapped:)];        [self addGestureRecognizer:tapRecognizer];                NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithCapacity:4];        self.imageViewArray = mutableArray;                NSMutableArray *overlayArray = [[NSMutableArray alloc] initWithCapacity:4];        self.overlayViewArray = overlayArray;    }    return self;}- (void)setAssets:(NSArray *)assets{    self.rowAssets = assets;    for (UIImageView *view in _imageViewArray) {        [view removeFromSuperview];    }    for (UIImageView *view in _overlayViewArray) {        [view removeFromSuperview];    }    //set up a pointer here so we don't keep calling [UIImage imageNamed:] if creating overlays    UIImage *overlayImage = nil;    for (int i = 0; i < [_rowAssets count]; ++i) {                SJAsset *asset = [_rowAssets objectAtIndex:i];                if (i < [_imageViewArray count]) {            UIImageView *imageView = [_imageViewArray objectAtIndex:i];            imageView.image = [UIImage imageWithCGImage:asset.asset.thumbnail];        } else {            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:asset.asset.thumbnail]];            [_imageViewArray addObject:imageView];        }                if (i < [_overlayViewArray count]) {            UIImageView *overlayView = [_overlayViewArray objectAtIndex:i];            overlayView.hidden = asset.selected ? NO : YES;        } else {            if (overlayImage == nil) {                overlayImage = [UIImage imageNamed:@"Overlay.png"];            }            UIImageView *overlayView = [[UIImageView alloc] initWithImage:overlayImage];            [_overlayViewArray addObject:overlayView];            overlayView.hidden = asset.selected ? NO : YES;        }    }}- (void)cellTapped:(UITapGestureRecognizer *)tapRecognizer{    CGPoint point = [tapRecognizer locationInView:self];    CGFloat totalWidth = self.bounds.size.width;    CGFloat imageWidth = totalWidth / 4 - 2 ;    //计算间隙    CGFloat startX =  (totalWidth - imageWidth*4) / 5;    CGRect frame = CGRectMake(startX, 2, imageWidth, imageWidth);        for (int i = 0; i < [_rowAssets count]; ++i) {        if (CGRectContainsPoint(frame, point)) {            SJAsset *asset = [_rowAssets objectAtIndex:i];            asset.selected = !asset.selected;            UIImageView *overlayView = [_overlayViewArray objectAtIndex:i];            overlayView.hidden = !asset.selected;            break;        }        frame.origin.x = frame.origin.x + frame.size.width + startX;    }}//在Cell中添加对应的Image- (void)layoutSubviews{    CGFloat totalWidth = self.bounds.size.width;    CGFloat imageWidth = totalWidth / 4 - 2 ;    //计算间隙    CGFloat startX =  (totalWidth - imageWidth*4) / 5;    CGRect frame = CGRectMake(startX, 2, imageWidth, imageWidth);        for (int i = 0; i < [_rowAssets count]; ++i) {        //添加图片        UIImageView *imageView = [_imageViewArray objectAtIndex:i];        [imageView setFrame:frame];        [self addSubview:imageView];                //添加阴影图片,点击选中        UIImageView *overlayView = [_overlayViewArray objectAtIndex:i];        [overlayView setFrame:frame];        [self addSubview:overlayView];        //每个图片之间的间隙        frame.origin.x = frame.origin.x + frame.size.width + startX;    }}@end

4.2  图片对象地址以及是否被选择等标示为 实体

////  SJAsset.h//  HappyApp////  Created by LiShijia on 15/1/9.//  Copyright (c) 2015年 com.johnli. All rights reserved.//#import <Foundation/Foundation.h>#import <AssetsLibrary/AssetsLibrary.h>@interface SJAsset : NSObject@property (nonatomic,strong) ALAsset *asset;@property(nonatomic,assign) BOOL selected;@end

4.3 图片列表展现

////  SJImagePickerController.h//  HappyApp////  Created by LiShijia on 15/1/6.//  Copyright (c) 2015年 com.johnli. All rights reserved.//#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>#import <AssetsLibrary/AssetsLibrary.h>@interface SJImagePickerListController : UITableViewController@property (nonatomic,strong) NSMutableArray *assetGroups;@property (nonatomic,strong) ALAssetsLibrary *library;@end

////  SJImagePickerController.m//  HappyApp////  Created by LiShijia on 15/1/6.//  Copyright (c) 2015年 com.johnli. All rights reserved.//#import "SJImagePickerListController.h"#import "SJImagePickerController.h"@implementation SJImagePickerListController-(void) viewDidLoad{    [super viewDidLoad];        //ALAssetsGroup类是系统用于映射相册资源中的每个相册,可以通过该类获取相册中的资源文件,并且能向相册中添加资源文件        //保存图片到系统默认的相册中,使用cgimageref的形式,并且选择图片以什么旋转方向的形式保存,并返回照片的url地址        //设置头部点击按钮    [self.navigationItem  setTitle:@"加载中"];    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelImagePicker)];    [self.navigationItem setRightBarButtonItem:cancelBtn];        NSMutableArray *tempArray = [[NSMutableArray alloc] init];        ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];        self.assetGroups = tempArray;    self.library = assetLibrary;        dispatch_async(dispatch_get_main_queue(), ^{            //block        void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop){                        if(group == nil){                return;            }                        NSString *sGroupPropertyName = (NSString *) [group valueForProperty:ALAssetsGroupPropertyName];            NSUInteger nType = [[group valueForProperty:ALAssetsGroupPropertyType] intValue];                        if ([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] && nType == ALAssetsGroupSavedPhotos)  {                [self.assetGroups insertObject:group atIndex:0];            }else{                [self.assetGroups addObject:group];            }                        [self performSelectorOnMainThread:@selector(reloadTableView) withObject:nil waitUntilDone:YES];        };                void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error){            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"error message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];            [alert show];        };                //通过ALAssetsLibrary迭代取出所有相册        [self.library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock:assetGroupEnumberatorFailure];                        });        }-(void) reloadTableView{    [self.tableView reloadData];    [self.navigationItem setTitle:@"Select An Album"];    }-(void) cancelImagePicker{    [self dismissViewControllerAnimated:YES completion:nil];}-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{    return 1;}-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return [self.assetGroups count];    }-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *cellIdentifier = @"Cell";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];    if (cell == nil) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];    }        ALAssetsGroup *group = (ALAssetsGroup *)[self.assetGroups objectAtIndex:indexPath.row];    [group setAssetsFilter:[ALAssetsFilter allPhotos]];    NSInteger gCount = [group numberOfAssets];        cell.textLabel.text = [NSString stringWithFormat:@"%@ (%ld)",[group valueForProperty: ALAssetsGroupPropertyName],(long)gCount];    //根据CGI读取图片    [cell.imageView setImage:[UIImage imageWithCGImage: [(ALAssetsGroup *)[self.assetGroups objectAtIndex:indexPath.row] posterImage]]];    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];    return cell;}-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    //设置点击之后恢复到点击之前的效果    [tableView deselectRowAtIndexPath:indexPath animated:YES];        SJImagePickerController *picker = [[SJImagePickerController alloc] init];    picker.assetGroup = [self.assetGroups objectAtIndex:indexPath.row];    [picker.assetGroup setAssetsFilter:[ALAssetsFilter allPhotos]];        [self.navigationController pushViewController: picker animated:YES ];    }- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 57;}@end

4.4 相册Group 显示Controller

////  SJImagePickerController.h//  HappyApp////  Created by LiShijia on 15/1/9.//  Copyright (c) 2015年 com.johnli. All rights reserved.//#import <UIKit/UIKit.h>#import <AssetsLibrary/AssetsLibrary.h>@interface SJImagePickerController : UITableViewController@property (nonatomic, strong) ALAssetsGroup *assetGroup;@property (nonatomic, strong) NSMutableArray *sjAssets;@property (nonatomic, strong) IBOutlet UILabel *selectedAssetsLabel;@property (nonatomic, assign) BOOL singleSelection;@property (nonatomic, assign) BOOL immediateReturn;@property (nonatomic, assign) int columns;@end

////  SJImagePickerController.m//  HappyApp////  Created by LiShijia on 15/1/9.//  Copyright (c) 2015年 com.johnli. All rights reserved.//#import "SJImagePickerController.h"#import "SJAsset.h"#import "SJAssetCell.h"@implementation SJImagePickerController-(void) viewDidLoad{    [super viewDidLoad];        //设置tableView的样式 UITableViewCellSeparatorStyleNone 空白的样式无分割线    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];    [self.tableView setAllowsSelection:NO];        NSMutableArray *tempArray = [[NSMutableArray alloc] init];    self.sjAssets = tempArray;        if (self.immediateReturn) {            }else{        UIBarButtonItem *doneButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneAction:)];        [self.navigationItem setRightBarButtonItem:doneButtonItem];        [self.navigationItem setTitle:@"Loading Image"];            }        //准备工作,初始化数据,通过Alssets 加载数据 开始加载页面    [self performSelectorInBackground:@selector(preparePhoto) withObject:nil];}- (void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated];    self.columns = self.view.bounds.size.width / 80;}-(void) doneAction:(id) sender{    NSMutableArray *selectedImages = [[NSMutableArray alloc] init];        for (NSObject *obj in self.sjAssets) {        if (YES) {            [selectedImages addObject:obj];        }    }    }-(void) preparePhoto{    [self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index,BOOL *stop){        if (result == nil) {            return;        }                SJAsset *sjAsset = [[SJAsset alloc] init];        [sjAsset setAsset:result];        //        BOOL isAssetFiltered = NO;//        if (self.assetPickerFilterDelegate &&//            [self.assetPickerFilterDelegate respondsToSelector:@selector(assetTablePicker:isAssetFilteredOut:)])//        {//            isAssetFiltered = [self.assetPickerFilterDelegate assetTablePicker:self isAssetFilteredOut:(ELCAsset*)elcAsset];//        }//        //        if (!isAssetFiltered) {            //所有图片集合            [self.sjAssets addObject:sjAsset];//        }            }];        dispatch_async(dispatch_get_main_queue(), ^{        //通过block 使tableView加载数据        [self.tableView reloadData];        long section = [self numberOfSectionsInTableView:self.tableView] -1 ;        long row = [self tableView: self.tableView numberOfRowsInSection:section] -1 ;        if (section >= 0 && row >= 0 ) {            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];        }                [self.navigationItem setTitle:@"Picker photo"];    });}-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{    return 1;}-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    if (self.columns <=0 ) {        self.columns = 4;    }    //根据数据集计算行数    NSInteger numRows = ceil([self.sjAssets count]/(float)self.columns);    return numRows;}//获取每行数据返回- (NSArray *)assetsForIndexPath:(NSIndexPath *)path{    long index = path.row * self.columns;    //根据行数获取最小数值    long length = MIN(self.columns, [self.sjAssets count] - index);    //这样就获得了这个数组中0开始的5个元素的子集。    //subarrayWithRange:NSMakeRange(0, 5)    return [self.sjAssets subarrayWithRange:NSMakeRange(index, length)];}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString * cellIdentifier = @"Cell";    SJAssetCell *cell = (SJAssetCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];    if (cell == nil) {        cell = [[SJAssetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];    }        //计算每行数据并显示    [cell setAssets: [self assetsForIndexPath:indexPath]];        return  cell;    }//计算Cell高度-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{        return  self.view.frame.size.width / 4;}@end





0 0
原创粉丝点击