欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-17 19:09:40
照例先上效果图 本次用的第三方框架做这个,但是需要考虑的地方也比较多,怎么把拍照和相册选取结合、删除照片后添加新照片时候的相册状态等等,所有的改变都是在操作数组。还需...

照例先上效果图

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能有一定的帮助,如果有疑问大家可以留言交流。

上一篇:

下一篇: