IOS开发相册图片多选和删除的功能_IOS

照例先上效果图

本次用的第三方框架做这个,但是需要考虑的地方也比较多,怎么把拍照和相册选取结合、删除照片后添加新照片时候的相册状态等等,所有的改变都是在操作数组。还需考虑图片的压缩上传。

本次用的第三方框架为: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能有一定的帮助,如果有疑问大家可以留言交流。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索ios开发
, 删除相册图片
, ios调用系统相册
多选
ios开发相册多选图片、ios开发相册多选、安卓开发 相册多选、ios开发 删除相册图片、ios相册多选,以便于您获取更多的相关知识。

时间: 2024-10-04 19:16:42

IOS开发相册图片多选和删除的功能_IOS的相关文章

IOS开发代码分享之用nstimer实现倒计时功能_IOS

用nstimer实现倒计时功能,废话不多说,直接上代码,详细解释请参照注释 // [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];   // - (void)timerFireMethod:(NSTimer *)theTimer {     BOOL timeStart = YES;     NSCalend

image-求救关于相册图片上传和删除

问题描述 求救关于相册图片上传和删除 UIImageView右上角有一个叉号,点击这个叉号删除image,怎么弄

POST请求,iOS开发时,图片上传的时候,类型是文件流,怎么写

问题描述 POST请求,iOS开发时,图片上传的时候,类型是文件流,怎么写 POST请求,iOS开发时,图片上传的时候,类型是文件流,怎么写,在线等 解决方案 http://blog.csdn.net/zhangkongzhongyun/article/details/8277426 解决方案二: 给个思路就行,或者给个链接

ios开发为图片添加中文水印的例子

先看一个效果图. 开发为图片添加中文水印的例子-ios开发图片添加水印">  看似简单,其实不然.下面我就跟大家分享下我做这个demo中遇到的一些坑,相信对于和我一样的IOS开发初学者一定会有帮助. 首先,我最初采用的一种方式,是使用 CGBitmapContextCreate 创建 context ,然后使用 CGContextSelectFont 设置字体和字号,最后使用 CGContextShowTextAtPoint 将水印合成到上下文,再调用 CGBitmapContextCre

IOS开发之适配iOS10及Xcode8的注意点_IOS

下面给大家介绍下iOS10的适配及Xcode8使用上的一些注意点,一起看看! 一.证书管理 用Xcode8打开工程后,比较明显的就是下图了,这个是苹果的新特性,可以帮助我们自动管理证书.建议大家勾选这个Automatically manage signing(Ps.但是在beat2版本我用的时候,完全不可以,GM版本竟然神奇的又好了.) 下面我来说说可能会出现的问题: 1.Xcode未设置开发者账号情况下的截图 解决办法是:大家在Xcode的偏好设置中,添加苹果账号,即可. 2.设备机器未添加进

iOS开发中简单实用的几个小技巧_IOS

前言 本文记录了在iOS开发过程中所遇到的小知识点,以及一些技巧,下面话不多说,来看看详细的介绍. 技巧1:UIButton图片与文字默认是左右排列,如何实现右左排列? 解决技巧: button.transform = CGAffineTransformMakeScale(-1.0, 1.0); button.titleLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0); button.imageView.transform = CGA

iOS开发笔记--详解UILabel的相关属性设置_IOS

在iOS编程中UILabel是一个常用的控件,下面分享一下UILabel的相关属性设置的方法. 很多学习iOS6编程都是从storyboard开始,用到UILabel时是将控件拖到storyboard中生成实现,如果想要在-(void)viewDidLoad中用代码如[_label initWithFrame:CGRectMake(X,Y,WIDTH,HEIGHT)]方法改变拖拽到storyboard的label的大小是行不通的,因为程序加载时先执行了-(void)viewDidLoad的代码,

iOS开发中不合法的网络请求地址如何解决_IOS

NSString *const kWebsite = @http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fr=&sf=1&fmq=1459502303089_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&

IOS开发代码分享之设置UISearchBar的背景颜色_IOS

今天用到UISearchBar,之前网上提供的方法已经不能有效的去除掉它的背景色了,修改背景色方法如下: mySearchBar.backgroundColor = RGBACOLOR(249,249,249,1);     mySearchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:mySearchBar.bounds.size];   //取消searchbar背景色 - (UIImage *)im