QB/UIImagePickerController

参考文档1
参考文档2

QBImagePickerController 相当于对UIImagePickerController的扩展,用法也相似。一般通过相机获取图片用UIImagePickerController,而多选 图片则直接使用QBImagePickerController更方便一些。但在使用过过各程中涉及很多图片相关知识。(关于权限)


QB/UIImagePickerController_第1张图片

viewController.m

#import "ViewController.h"
#import 
#import "UpLoadImageCell.h"
#import "ShowEditItem.h"

//ASSet需要导入
#import 
#import 
#import 
#import 


@interface ViewController ()
@property (nonatomic,retain) UIImagePickerController *imagePickerController;
@property (nonatomic,retain) QBImagePickerController *picker;
@property (nonatomic,retain) ShowEditItem *showEditItem;
@property (nonatomic,retain) UITableView *tableView;
@end

生命周期

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
}

懒加载

#pragma mark - 懒加载
- (UITableView*)tableView{
    if (!_tableView) {
        
        _tableView  = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor lightGrayColor];
        _tableView.tableFooterView=[UIView new];

        //注册单元格
        [_tableView registerClass:[UpLoadImageCell class] forCellReuseIdentifier:NSStringFromClass([UpLoadImageCell class])];
    }
    return _tableView;
}
- (QBImagePickerController*)picker{
    if (!_picker) {
        _picker = [[QBImagePickerController alloc]init];
        _picker.delegate = self;
        _picker.automaticallyAdjustsScrollViewInsets = YES;
        _picker.minimumNumberOfSelection = 1;
        _picker.maximumNumberOfSelection = 11;
        //指定显示的相册
        _picker.assetCollectionSubtypes = @[                               @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
            //@(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
            //@(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景图
            //@(PHAssetCollectionSubtypeSmartAlbumVideos), //视频
            //@(PHAssetCollectionSubtypeSmartAlbumBursts) //连拍模式拍摄的照片
            ];
        //设置媒体类型
        _picker.mediaType = QBImagePickerMediaTypeAny;//图片与视频
        //设置每行显示的图像数量
        _picker.numberOfColumnsInPortrait = 4;//竖屏下每行4个
        _picker.numberOfColumnsInLandscape = 7;//横惬意下每行7个
        _picker.prompt = @"请选择图片";
        _picker.showsNumberOfSelectedAssets = YES;
        _picker.allowsMultipleSelection = YES;
    }
    [_picker.selectedAssets removeAllObjects];
    [_picker.selectedAssets addObjectsFromArray:self.showEditItem.selectedAssets];
    return _picker;
}
- (UIImagePickerController*)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController  = [[UIImagePickerController alloc] init];
       _imagePickerController.delegate = self;
       _imagePickerController.allowsEditing = NO;//设置可编辑
    }
    return _imagePickerController;
}
- (ShowEditItem*)showEditItem{
    if (!_showEditItem) {
        _showEditItem = [[ShowEditItem alloc]init];
        _showEditItem.selectedImages = [NSMutableArray array];
        _showEditItem.selectedAssets = [NSMutableArray array];
    }
    return _showEditItem;
}

弹框选择

#pragma mark - UIAlertController
- (void)showActionForPhoto{
    
     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择照片路径" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"该设备不支持相机");
        }else{
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self.navigationController presentViewController:self.imagePickerController
                                                    animated:YES
                                                  completion:nil];
        }
    }];
    
    
    UIAlertAction *cameroAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            NSLog(@"该设备不支持从相册选取文件");
        }else{
           
            [self presentViewController:self.picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:photoAction];
    [alertController addAction:cameroAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

拍照的回调方法

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *pickerImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    //添加照片
    [self.showEditItem.selectedImages addObject:pickerImage];
    [self.tableView reloadData];
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{}];  
}

相册回调方法

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
           //清数据
        [self.showEditItem.selectedImages removeAllObjects];
        [self.showEditItem.selectedAssets removeAllObjects];
        
        if (assets.count == 0) {
            [self.tableView reloadData];
            [self dismissViewControllerAnimated:YES completion:nil];
            return ;
        }
        
        //将选好的图片资源存入数组
        //1.PHAsset数组
        [self.showEditItem.selectedAssets addObjectsFromArray:assets];
        //2.照片数组
        for (PHAsset *asset in self.showEditItem.selectedAssets) {
            
            
            [[PHImageManager defaultManager]requestImageForAsset:asset
                                                      targetSize:CGSizeMake(asset.pixelWidth, asset.pixelHeight)
                                                     contentMode:PHImageContentModeDefault
                                                         options:nil
                                                   resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                            [self.showEditItem.selectedImages addObject:result];
                                                   }];
            
        }
  
    [self.tableView reloadData];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

tableView 的代理方法

#pragma mark-tableview的代理方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
       //Cell中的是collectionView
       return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    __weak typeof(self) weakSelf = self;
    UpLoadImageCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UpLoadImageCell class]) forIndexPath:indexPath];
    //每次刷新都会调用cell方法
    //每次调用cell的setShowEditItem方法都会刷新collectionView
    [cell setShowEditItem:self.showEditItem];
    
    cell.addPictureBlock = ^(){
        [weakSelf showActionForPhoto];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.view.frame.size.height;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

UpLoadImageCell相关

.h文件
#import 
#import "ShowEditItem.h"
#import "ShowImageCell.h"

@interface UpLoadImageCell : UITableViewCell
@property (nonatomic,retain) ShowEditItem *showEditItem;
@property (nonatomic,copy) void(^addPictureBlock)();//应该多尝试用block
@end
.m文件
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
//每行4个图片,间距10,左右两边15
#define kShowImageCCell_Width floorf((SCREEN_WIDTH - 15*2- 10*3)/4)

#import "UpLoadImageCell.h"
#import "ShowImageCell.h"

@interface UpLoadImageCell ()

@property (strong, nonatomic) UICollectionView    *collectionView;
@property (strong, nonatomic) NSMutableDictionary *imageViewsDict;

@property (strong, nonatomic) NSArray *imgs;
@property (weak, nonatomic)  UIButton *deleteBtn;
@end
主要代码
-(void)setShowEditItem:(ShowEditItem *)item{
    
    //cell 用传过来的item 刷新页面
    _showEditItem = item;
    [self.collectionView reloadData];//传值即刷新,很重要
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.frame = [UIScreen mainScreen].bounds;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //集合视图
        [self setupCollectionView];
    }
    return self;
}

-(void)setupCollectionView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(kShowImageCCell_Width, kShowImageCCell_Width);
    
    //这个frame高度最好写活
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(15, 10, SCREEN_WIDTH - 2 * 15, 300) collectionViewLayout:layout];
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.scrollEnabled = NO;
    [self.collectionView setBackgroundColor:[UIColor redColor]];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([ShowImageCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([ShowImageCell class])];
    
    [self.contentView addSubview:self.collectionView];
}

#pragma mark -
#pragma mark - UICollectionViewDelegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //限制最大上传9张图片
    NSInteger num = self.showEditItem.selectedImages.count;
    return num < 9 ? num+ 1: num;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ShowImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ShowImageCell" forIndexPath:indexPath];
    cell.deleteBtn.layer.cornerRadius = 15;
    cell.deleteBtn.layer.masksToBounds = 15;
    cell.deleteBtn.backgroundColor = [UIColor colorWithRed:0.08 green:0.44 blue:0.87 alpha:1.00];
    [cell.deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    if (indexPath.row < self.showEditItem.selectedImages.count) {
        cell.img.image = self.showEditItem.selectedImages[indexPath.row];
        cell.deleteBtn.hidden = NO;
        
    }else{
        cell.deleteBtn.hidden = YES;
        cell.img.image = [UIImage imageNamed:@"WechatIMG20.jpeg"];
    }
    
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}


//点击增加图片
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //判断是点击查看大图还是点击新增图片
    if (indexPath.row == self.showEditItem.selectedImages.count ) {
            if (_addPictureBlock) {
                _addPictureBlock();
            }
    }
}

//删除图片
-(void)deleteBtnClick:(UIButton *)btn{
    
    NSInteger index = btn.tag;
    [self.showEditItem.selectedImages removeObjectAtIndex:index];
    [self.showEditItem.selectedAssets removeObjectAtIndex:index];
    //清除图片元素后刷新
    [self setShowEditItem:self.showEditItem];
}

@end

你可能感兴趣的:(QB/UIImagePickerController)