当前位置: 移动技术网 > IT编程>移动开发>IOS > IOS开发相册图片多选和删除的功能

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

乐农网,中国有多少人口,世界拳王泰森

照例先上效果图

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

本次用的第三方框架为: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 uicollectionview实现横向滚动

    现在使用卡片效果的app很多,之前公司让实现一种卡片效果,就写了一篇关于实现卡片的文章。文章最后附有demo实现上我选择了使用uicollectionview ... [阅读全文]
  • iOS UICollectionView实现横向滑动

    本文实例为大家分享了ios uicollectionview实现横向滑动的具体代码,供大家参考,具体内容如下uicollectionview的横向滚动,目前我使... [阅读全文]
  • iOS13适配深色模式(Dark Mode)的实现

    iOS13适配深色模式(Dark Mode)的实现

    好像大概也许是一年前, mac os系统发布了深色模式外观, 看着挺刺激, 时至今日用着也还挺爽的终于, 随着iphone11等新手机的发售, ios 13系统... [阅读全文]
  • ios 使用xcode11 新建项目工程的步骤详解

    ios 使用xcode11 新建项目工程的步骤详解

    xcode11新建项目工程,新增了scenedelegate这个类,转而将原appdelegate负责的对ui生命周期的处理担子接了过来。故此可以理解为:ios... [阅读全文]
  • iOS实现转盘效果

    本文实例为大家分享了ios实现转盘效果的具体代码,供大家参考,具体内容如下demo下载地址: ios转盘效果功能:实现了常用的ios转盘效果,轮盘抽奖效果的实现... [阅读全文]
  • iOS开发实现转盘功能

    本文实例为大家分享了ios实现转盘功能的具体代码,供大家参考,具体内容如下今天给同学们讲解一下一个转盘选号的功能,直接上代码直接看viewcontroller#... [阅读全文]
  • iOS实现轮盘动态效果

    本文实例为大家分享了ios实现轮盘动态效果的具体代码,供大家参考,具体内容如下一个常用的绘图,主要用来打分之类的动画,效果如下。主要是ios的绘图和动画,本来想... [阅读全文]
  • iOS实现九宫格连线手势解锁

    本文实例为大家分享了ios实现九宫格连线手势解锁的具体代码,供大家参考,具体内容如下demo下载地址:效果图:核心代码://// clockview.m// 手... [阅读全文]
  • iOS实现卡片堆叠效果

    本文实例为大家分享了ios实现卡片堆叠效果的具体代码,供大家参考,具体内容如下如图,这就是最终效果。去年安卓5.0发布的时候,当我看到安卓全新的material... [阅读全文]
  • iOS利用余弦函数实现卡片浏览工具

    iOS利用余弦函数实现卡片浏览工具

    本文实例为大家分享了ios利用余弦函数实现卡片浏览工具的具体代码,供大家参考,具体内容如下一、实现效果通过拖拽屏幕实现卡片移动,左右两侧的卡片随着拖动变小,中间... [阅读全文]
验证码:
移动技术网