// // ZKImageSelectView.h // ZKImageSelectAndBrowse // // Created by HELLO WORLD on 2019/9/18. // Copyright © 2019年 WaterProofer. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ZKImageSelectView : UIImageView //图片列表 @property (nonatomic, strong) NSMutableArray<UIImage*>* listImages; //最多可选择的图片数 @property (nonatomic, readwrite) int maxNumberOfImage; //是否允许编辑 @property (nonatomic, readwrite) BOOL allowEdit; @property (nonatomic, readwrite) BOOL allowScroll; @property (nonatomic, copy) void (^selectAddBtnCilck)(UIImage*); @property (nonatomic, copy) void (^selectDelBtnCilck)(NSInteger); @property (nonatomic, copy) void (^reloadHeight)(CGFloat); @end NS_ASSUME_NONNULL_END
// // ZKImageSelectView.m // ZKImageSelectAndBrowse // // Created by HELLO WORLD on 2019/9/18. // Copyright © 2019年 WaterProofer. All rights reserved. // #import "ZKImageSelectView.h" #import <Photos/Photos.h> #import <AssetsLibrary/AssetsLibrary.h> #import <Masonry.h> #import <TZImageManager.h> #import <TZImagePickerController.h> #import <IDMPhotoBrowser.h> #import <UIImageView+WebCache.h> #import "UIView+ZKFind.h" //获取屏幕 宽度、高度 #define ZKSCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width) @interface ZKImageSelectView ()<TZImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate> { UIButton* btnAdd; } @property (nonatomic, strong)UIImagePickerController* imagePickerVc; @property (assign, nonatomic) NSInteger iNumber; @end @implementation ZKImageSelectView - (id)init { if (self = [super init]) { self.userInteractionEnabled = YES; self.backgroundColor = [UIColor orangeColor]; self.listImages=[[NSMutableArray alloc] initWithCapacity:0]; } return self; } - (void)setListImages:(NSMutableArray<UIImage*>*)listImages { _listImages = listImages; self.iNumber = self.maxNumberOfImage - listImages.count; for (UIView* view in self.subviews){ [view removeFromSuperview]; } CGFloat top_distance = 10;//上下边距 CGFloat left_distance = 10;//左右边距 CGFloat borderWidth = 20;//图片之间的横向距离 CGFloat imgWidth = 60*ZKSCREEN_WIDTH/375;//图片大小 int j=0,h=0; for (int i=0; i<listImages.count; i++){ UIImageView* smallView = [UIImageView new]; smallView.tag=i; [smallView setContentMode:UIViewContentModeScaleAspectFill]; smallView.clipsToBounds = YES; if ([listImages[i] isKindOfClass:[UIImage class]]) { [smallView setImage:listImages[i]]; }else{ [smallView sd_setImageWithURL:[NSURL URLWithString:(NSString*)listImages[i]]]; } [self addSubview:smallView]; [smallView mas_updateConstraints:^(MASConstraintMaker *make){ make.top.mas_offset(j*(imgWidth+borderWidth)+top_distance); make.left.mas_offset(h*(imgWidth+borderWidth)+left_distance); make.size.mas_equalTo(CGSizeMake(imgWidth,imgWidth)); }]; smallView.userInteractionEnabled = YES; UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cell_Click:)]; [smallView addGestureRecognizer:tap]; if (self.allowEdit){ //右上角删除btn UIButton* btnDel = [UIButton new]; [self addSubview:btnDel]; [btnDel mas_makeConstraints:^(MASConstraintMaker* make) { make.centerX.equalTo(smallView.mas_right).offset(0); make.centerY.equalTo(smallView.mas_top).offset(0); make.size.mas_equalTo(CGSizeMake(30, 30)); }]; btnDel.tag = i; [btnDel setImage:[UIImage imageNamed:@"hire_close_icon"] forState:UIControlStateNormal]; [btnDel addTarget:self action:@selector(btnDel_Click:) forControlEvents:UIControlEventTouchUpInside]; } if((ZKSCREEN_WIDTH-left_distance*2)-((h+1)*(imgWidth+borderWidth))<imgWidth){ j++; h=0; [self mas_updateConstraints:^(MASConstraintMaker *make){ make.height.mas_equalTo(j*(imgWidth+borderWidth)+imgWidth+top_distance*2); }]; if (self.reloadHeight) { self.reloadHeight(j*(imgWidth+borderWidth)+imgWidth+top_distance*2); } }else{ h++; } } if(listImages.count< self.maxNumberOfImage){ btnAdd = [UIButton buttonWithType:UIButtonTypeCustom]; btnAdd.adjustsImageWhenHighlighted = NO;//取消高亮状态下t颜色变深的效果 [btnAdd setBackgroundImage:[UIImage imageNamed:@"hire_add_icon"] forState:UIControlStateNormal]; [btnAdd addTarget:self action:@selector(btnAdd_Click) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:btnAdd]; [btnAdd mas_makeConstraints:^(MASConstraintMaker* make){ make.top.mas_offset(j*(imgWidth+borderWidth)+top_distance); make.left.mas_offset(h*(imgWidth+borderWidth)+left_distance); make.size.mas_equalTo(CGSizeMake(imgWidth,imgWidth)); }]; [self mas_updateConstraints:^(MASConstraintMaker *make) { make.height.mas_equalTo(j*(imgWidth+borderWidth)+imgWidth+top_distance*2); }]; if (self.reloadHeight) { self.reloadHeight(j*(imgWidth+borderWidth)+imgWidth+top_distance*2); } } } -(void)cell_Click:(UITapGestureRecognizer*)sender{ NSMutableArray<UIImage*>* arrImage = [[NSMutableArray alloc] initWithArray:self.listImages]; [self presentViewController:arrImage index:sender.view.tag]; // if (self.selectDelBtnCilck) { // self.selectDelBtnCilck(sender.view.tag); // } } -(void)presentViewController:(NSArray *)mutArr index:(NSInteger)index{ // NSArray* photosWithURL = [IDMPhoto photosWithURLs:mutArr]; NSArray* photosWithImages = [IDMPhoto photosWithImages:mutArr]; NSMutableArray* photos = [NSMutableArray arrayWithArray:photosWithImages]; IDMPhotoBrowser* browser = [[IDMPhotoBrowser alloc] initWithPhotos:photos]; browser.dismissOnTouch = YES; browser.displayArrowButton = NO; browser.displayActionButton = NO; browser.displayDoneButton = NO; browser.autoHideInterface = NO; browser.displayCounterLabel = YES; browser.useWhiteBackgroundColor = NO; browser.usePopAnimation=YES; browser.scaleImage = mutArr[index]; browser.trackTintColor = [UIColor colorWithWhite:0.8 alpha:1]; [browser setInitialPageIndex:index]; [self.containingViewController presentViewController:browser animated:YES completion:nil]; } - (void)btnDel_Click:(UIButton*)button { NSMutableArray<UIImage*>* arrImage = [[NSMutableArray alloc] initWithArray:self.listImages]; [arrImage removeObjectAtIndex:button.tag]; self.listImages = arrImage; // if (self.selectDelBtnCilck) { // self.selectDelBtnCilck(button.tag); // } } -(void)setMaxNumberOfImage:(int)maxNumberOfImage{ _maxNumberOfImage = maxNumberOfImage; self.iNumber = maxNumberOfImage; self.listImages = [[NSMutableArray alloc] initWithCapacity:0]; } #pragma mark -- 调用相机、相册 - (void)btnAdd_Click { __weak typeof(self)wself = self; UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *action = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [wself pushImagePickerController]; }]; [alert addAction:action]; UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [wself TakePictures]; }]; [alert addAction:action1]; UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { }]; [alert addAction:cancel]; [self.containingViewController presentViewController:alert animated:YES completion:nil]; } #pragma mark - TZImagePickerController - (void)pushImagePickerController{ __weak typeof(self)wself= self; TZImagePickerController* imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:self.maxNumberOfImage-self.listImages.count delegate:wself]; imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮 // 设置是否可以选择视频/图片/原图 imagePickerVc.allowPickingVideo = NO; [self.containingViewController presentViewController:imagePickerVc animated:YES completion:nil]; } //选完照片 - (void)imagePickerController:(TZImagePickerController*)picker didFinishPickingPhotos:(NSArray*)photos sourceAssets:(NSArray*)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto { NSMutableArray* arr = [NSMutableArray arrayWithArray:self.listImages]; for (UIImage* image in photos) { [arr addObject:image]; } self.listImages = arr; // if (self.selectAddBtnCilck) { // self.selectAddBtnCilck(nil); // } } //打开相机 -(void)TakePictures{ AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]; [alert addAction:action]; [self.containingViewController presentViewController:alert animated:YES completion:nil]; }else{ // 调用相机 UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { self.imagePickerVc.sourceType = sourceType; self.imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext; [self.containingViewController presentViewController:_imagePickerVc animated:YES completion:nil]; }else{ //NSLog(@"模拟器中无法打开照相机,请在真机中使用"); } } } - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info { [picker dismissViewControllerAnimated:YES completion:nil]; NSString* type = [info objectForKey:UIImagePickerControllerMediaType]; if ([type isEqualToString:@"public.image"]) { TZImagePickerController* tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:(self.maxNumberOfImage - self.listImages.count) delegate:self]; [tzImagePickerVc showProgressHUD]; UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage]; // save photo and get asset / 保存图片,获取到asset [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) { [[TZImageManager manager] getCameraRollAlbum:YES allowPickingImage:YES needFetchAssets:YES completion:^(TZAlbumModel *model) { [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel*>* models) { [tzImagePickerVc hideProgressHUD]; TZAssetModel* assetModel = [models firstObject]; if (tzImagePickerVc.sortAscendingByModificationDate) { assetModel = [models lastObject]; } NSMutableArray* arr = [NSMutableArray arrayWithArray:self.listImages]; [arr addObject:image]; self.listImages = arr; // if (self.selectAddBtnCilck) { // self.selectAddBtnCilck(nil); // } }]; }]; }]; } } - (UIImagePickerController*)imagePickerVc { if (_imagePickerVc == nil) { _imagePickerVc = [[UIImagePickerController alloc] init]; _imagePickerVc.delegate = self; // set appearance / 改变相册选择页的导航栏外观 _imagePickerVc.navigationBar.barTintColor = self.containingViewController.navigationController.navigationBar.barTintColor; _imagePickerVc.navigationBar.tintColor = self.containingViewController.navigationController.navigationBar.tintColor; UIBarButtonItem *tzBarItem, *BarItem; tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[ [TZImagePickerController class] ]]; BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[ [UIImagePickerController class] ]]; NSDictionary* titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal]; [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal]; } return _imagePickerVc; } @end
ZKImageSelectView* selectView = [[ZKImageSelectView alloc]init]; selectView.maxNumberOfImage = 6; selectView.allowEdit = YES; [self.view addSubview:selectView]; [selectView mas_makeConstraints:^(MASConstraintMaker* make) { make.width.mas_equalTo(self.view.mas_width); make.top.offset(100); }];
原文:https://www.cnblogs.com/kingstudy/p/11545091.html