IOS開發相簿圖片多選和刪除的功能_IOS

來源:互聯網
上載者:User

照例先上效果圖

本次用的第三方架構做這個,但是需要考慮的地方也比較多,怎麼把拍照和相簿選取結合、刪除照片後添加新照片時候的相簿狀態等等,所有的改變都是在運算元組。還需考慮圖片的壓縮上傳。

本次用的第三方架構為:QBImagePickerController

按照慣例,上代碼,本次代碼較多

第一個控制器 .h裡沒啥代碼

#import "RRZShowEditViewController.h"#import "RRZSendShowTextCell.h"#import "RRZSendShowImageCell.h"#import "QBImagePickerController.h"#import "ShowEditItem.h"static NSString *sendShowTextCellID = @"SendShowTextCellID";static NSString *sendShowImageCellID = @"SendShowImageCellID";@interface RRZShowEditViewController ()<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIScrollViewDelegate,UIActionSheetDelegate,QBImagePickerControllerDelegate>@property (strong, nonatomic) UITableView *myTableView;/** model*/@property (strong, nonatomic) ShowEditItem *showEditItem;/** textView的text*/@property (strong, nonatomic) NSString *valueStr;/** 文本輸入*/@property (weak, nonatomic) NumberofwordsTextView *textView;@property (strong, nonatomic) QBImagePickerController *imagePickerController;@end@implementation RRZShowEditViewController-(ShowEditItem *)showEditItem{  if (!_showEditItem) {    _showEditItem = [[ShowEditItem alloc]init];    _showEditItem.selectedImages = @[].mutableCopy;    _showEditItem.selectedAssetURLs = @[].mutableCopy;  }  return _showEditItem;}-(QBImagePickerController *)imagePickerController{  if (!_imagePickerController) {    _imagePickerController = [[QBImagePickerController alloc] init];    _imagePickerController.filterType = QBImagePickerControllerFilterTypePhotos;    _imagePickerController.delegate = self;    _imagePickerController.allowsMultipleSelection = YES;    _imagePickerController.maximumNumberOfSelection = 9;  }  [_imagePickerController.selectedAssetURLs removeAllObjects];  [_imagePickerController.selectedAssetURLs addObjectsFromArray:self.showEditItem.selectedAssetURLs];  return _imagePickerController;}-(void)viewWillAppear:(BOOL)animated{  [super viewWillAppear:animated];}-(void)viewDidAppear:(BOOL)animated{  [super viewDidAppear:animated];}- (void)viewDidLoad {  [super viewDidLoad];  self.title = @"曬一曬";  [self setupTabelView];  [self setupNavItem];}-(void)setupNavItem{  UIBarButtonItem *rightItem = [UIBarButtonItem itemWithTitle:@"發布" highTitle:nil target:self action:@selector(sendClick) norColor:NavItemColor highColor:RGB_COLOR(200, 200, 200)];  self.navigationItem.rightBarButtonItem = rightItem;}// 壓縮圖片- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize{  //先調整解析度  CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);  CGFloat tempHeight = newSize.height / 1024;  CGFloat tempWidth = newSize.width / 1024;  if (tempWidth > 1.0 && tempWidth > tempHeight) {    newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);  }  else if (tempHeight > 1.0 && tempWidth < tempHeight){    newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);  }  UIGraphicsBeginImageContext(newSize);  [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();  UIGraphicsEndImageContext();  //調整大小  NSData *imageData;  if (UIImagePNGRepresentation(newImage)) {    imageData = UIImagePNGRepresentation(newImage);  }else{    imageData = UIImageJPEGRepresentation(newImage, 0.5);  }  NSUInteger sizeOrigin = [imageData length];  NSUInteger sizeOriginKB = sizeOrigin / 1024;  if (sizeOriginKB > maxSize) {    NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50);    return finallImageData;  }  return imageData;}-(void)sendClick{  [self.view endEditing:YES];  [HUDController showProgressLabel:@""];  NSString *textStr = self.textView.text;  textStr = [textStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];  if (textStr.length > 0 || self.showEditItem.selectedImages.count > 0) {    DLog(@"發表曬一曬");    NSMutableArray *tempImages = [[NSMutableArray alloc]init];    for (int i = 0; i < self.showEditItem.selectedImages.count; i++) {      UIImage *tempImage = self.showEditItem.selectedImages[i];      NSData *imgData = [self resetSizeOfImageData:tempImage maxSize:150];      tempImage = [UIImage imageWithData:imgData];      [tempImages addObject:tempImage];    }    [[RRZNetworkController sharedController]sendShowInfoByRemark:self.textView.text myfiles:tempImages success:^(NSDictionary *data) {      NSString *code = data[@"code"];      if ([code isEqualToString:@"success"]) {        [HUDController hideHUDWithText:@"發表成功"];        if (_sendSuccessBlock) {          _sendSuccessBlock();        }        [self.navigationController popViewControllerAnimated:YES];      }else{        [HUDController hideHUD];        NSString *message = data[@"message"];        if (message.length > 30) {          message = @"上傳失敗";        }        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil, nil];        [alertView show];      }    } failure:^(NSDictionary *error) {      [HUDController hideHUDWithText:NetworkError];    }];  }else{    [HUDController hideHUDWithText:@"文字或圖片不可為空"];  }}-(void)setupTabelView{  //  添加myTableView  _myTableView = ({    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];    tableView.backgroundColor = [UIColor clearColor];    tableView.dataSource = self;    tableView.delegate = self;    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;    [tableView registerClass:[RRZSendShowTextCell class] forCellReuseIdentifier:sendShowTextCellID];    [tableView registerClass:[RRZSendShowImageCell class] forCellReuseIdentifier:sendShowImageCellID];    [self.view addSubview:tableView];    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {      make.edges.equalTo(self.view);    }];    tableView;  });}#pragma mark - UITableViewDelegate-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{  return 2;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{  if (indexPath.row == 0) {    RRZSendShowTextCell *cell = [tableView dequeueReusableCellWithIdentifier:sendShowTextCellID];    self.textView = cell.numberTextView;//    cell.textValueChangedBlock = ^(NSString *valueStr){//      weakSelf.valueStr = valueStr;//    };    return cell;  }else{    RRZSendShowImageCell *cell = [tableView dequeueReusableCellWithIdentifier:sendShowImageCellID];    cell.item = self.showEditItem;    __weak typeof(self) weakSelf = self;    cell.addPicturesBlock = ^(){      [weakSelf showActionForPhoto];    };    cell.deleteImageBlock = ^(ShowEditItem *item){      weakSelf.showEditItem = item;      [weakSelf.myTableView reloadData];    };    return cell;  }}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{  if (indexPath.row == 0) {    return 200;  }else{    return 300;  }}#pragma mark UIActionSheet M- (void)showActionForPhoto{  UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"從相簿選取", nil];  [actionSheet showInView:self.view];}#pragma mark - UIActionSheetDelegate-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{  if (buttonIndex == 0) {    DLog(@"拍照");    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {      UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:@"該裝置不支援拍照" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:NULL];      [alert show];    }else{      UIImagePickerController *picker = [[UIImagePickerController alloc] init];      picker.delegate = self;      picker.allowsEditing = NO;//設定可編輯      picker.sourceType = UIImagePickerControllerSourceTypeCamera;      [self presentViewController:picker animated:YES completion:nil];//進入照相介面    }  }else if (buttonIndex == 1){    DLog(@"相簿");    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {      UIAlertView *alert= [[UIAlertView alloc] initWithTitle:nil message:@"該裝置不支援從相簿選取檔案" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:NULL];      [alert show];    }else{      UINavigationController *navigationController = [[BaseNavigationController alloc] initWithRootViewController:self.imagePickerController];      [self presentViewController:navigationController animated:YES completion:NULL];    }  }}#pragma mark UIImagePickerControllerDelegate// 拍照回調- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{  UIImage *pickerImage = [info objectForKey:UIImagePickerControllerOriginalImage];  [self.showEditItem.selectedImages addObject:pickerImage];  ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];  [assetsLibrary writeImageToSavedPhotosAlbum:[pickerImage CGImage] orientation:(ALAssetOrientation)pickerImage.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {    [self.showEditItem.selectedAssetURLs addObject:assetURL];//    [self.showEditItem addASelectedAssetURL:assetURL];    [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];  }];  [picker dismissViewControllerAnimated:YES completion:^{}];}- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{  [picker dismissViewControllerAnimated:YES completion:nil];}#pragma mark QBImagePickerControllerDelegate//相簿回調- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{  [self.showEditItem.selectedImages removeAllObjects];  NSMutableArray *selectedAssetURLs = [NSMutableArray new];  [imagePickerController.selectedAssetURLs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {    [selectedAssetURLs addObject:obj];  }];  self.showEditItem.selectedAssetURLs = selectedAssetURLs;  for (int i = 0; i < assets.count; i++) {    ALAsset *asset = assets[i];    UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];    [self.showEditItem.selectedImages addObject:tempImg];  }  @weakify(self);  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{    self.showEditItem.selectedAssetURLs = selectedAssetURLs;    dispatch_async(dispatch_get_main_queue(), ^{      @strongify(self);      [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];    });  });  [self dismissViewControllerAnimated:YES completion:nil];}- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{  [self dismissViewControllerAnimated:YES completion:nil];}#pragma mark - scrollView // 滾動結束編輯 收合鍵盤- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{  if (scrollView == self.myTableView) {    [self.view endEditing:YES];  }}- (void)dealloc{  _myTableView.delegate = nil;  _myTableView.dataSource = nil;}@end

第二個控制器 .h

#import <UIKit/UIKit.h>#import "NumberofwordsTextView.h"@interface RRZSendShowTextCell : UITableViewCell@property (weak, nonatomic) NumberofwordsTextView *numberTextView;@end

第二個控制器 .m

#define kTweetContentCell_ContentFont [UIFont systemFontOfSize:16]#import "RRZSendShowTextCell.h"@interface RRZSendShowTextCell()@end@implementation RRZSendShowTextCell- (void)awakeFromNib {  [super awakeFromNib];  // Initialization code  self.selectionStyle = UITableViewCellSelectionStyleNone;}- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{  self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];  if (self) {    NumberofwordsTextView *numberTextView = [[NumberofwordsTextView alloc] init];    numberTextView.frame = CGRectMake(7, 7, SCREEN_WIDTH-7*2, 180);    numberTextView.wordsMaxNumer = 300;    numberTextView.placeHolder = @"寫點什麼來曬一曬吧...";    numberTextView.textFont = [UIFont systemFontOfSize:14];    [self addSubview:numberTextView];    self.numberTextView = numberTextView;  }  return self;}@end

第三個 .h

#import <UIKit/UIKit.h>#import "ShowEditItem.h"@interface RRZSendShowImageCell : UITableViewCell@property (copy, nonatomic) void (^addPicturesBlock)();@property (copy, nonatomic) void (^deleteImageBlock)(ShowEditItem *toDelete);@property (nonatomic,strong) ShowEditItem *item;@end.m#define kShowImageCCell_Width floorf((SCREEN_WIDTH - 15*2- 10*3)/4)#import "RRZSendShowImageCell.h"#import "RRZShowEditImageCell.h"#import "UICustomCollectionView.h"static NSString *cellID = @"RRZShowImageCCellID";@interface RRZSendShowImageCell()<UICollectionViewDelegate,UICollectionViewDataSource>@property (strong, nonatomic) UICustomCollectionView *mediaView;@property (strong, nonatomic) NSMutableDictionary *imageViewsDict;/** <#注釋#>*/@property (strong, nonatomic) NSArray *imgs;/** <#注釋#>*/@property (weak, nonatomic) UIButton *deleteBtn;@end@implementation RRZSendShowImageCell-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{  if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {    self.height = 300;    [self setupCollectionView];    self.selectionStyle = UITableViewCellSelectionStyleNone;    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 20, 1)];    label.backgroundColor = RGB_COLOR(240, 240, 240);    [self.contentView addSubview:label];  }  return self;}-(void)setupCollectionView{  UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];  layout.itemSize = CGSizeMake(kShowImageCCell_Width, kShowImageCCell_Width);  self.mediaView = [[UICustomCollectionView alloc]initWithFrame:CGRectMake(15, 10, SCREEN_WIDTH - 2 * 15, 280) collectionViewLayout:layout];  self.mediaView.scrollEnabled = NO;  [self.mediaView setBackgroundColor:[UIColor clearColor]];  [self.mediaView registerNib:[UINib nibWithNibName:NSStringFromClass([RRZShowEditImageCell class]) bundle:nil] forCellWithReuseIdentifier:cellID];  self.mediaView.dataSource = self;  self.mediaView.delegate = self;  [self.contentView addSubview:self.mediaView];}-(void)setItem:(ShowEditItem *)item{  _item = item;  [self.mediaView reloadData];}#pragma mark - UICollectionViewDelegate-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{  NSInteger num = self.item.selectedImages.count;  return num < 9? num+ 1: num;}-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{  RRZShowEditImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];  if (indexPath.row < self.item.selectedImages.count) {    cell.img = self.item.selectedImages[indexPath.row];  }else{    cell.img = nil;  }  cell.deleteBtn.tag = indexPath.row;  [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];  self.deleteBtn = cell.deleteBtn;  return cell;}-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{  if (indexPath.row == self.item.selectedAssetURLs.count || indexPath.row == self.item.selectedImages.count) {    if (_addPicturesBlock) {      _addPicturesBlock();    }  }}-(void)deleteBtnClick:(UIButton *)btn{  NSInteger index = btn.tag;  [self.item.selectedImages removeObjectAtIndex:index];  [self.item.selectedAssetURLs removeObjectAtIndex:index];  if (_deleteImageBlock) {    _deleteImageBlock(_item);  }}@end

RRZShowEditImageCell.h 就不寫了,就是自訂一個UICollectionViewCell

NumberofwordsTextView 在文中也用到了,就不貼代碼了

總結

以上就是從相機或相簿選取多圖上傳的代碼實現,其他的描述就不寫了,希望這篇文章對大家開發IOS能有一定的協助,如果有疑問大家可以留言交流。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.