服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - IOS开发相册图片多选和删除的功能

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

2021-01-25 16:09Berton_Yi IOS

之前小编有和大家分享过一篇关于从相册选取单张照片的文章,那么下面这篇文章跟大家分享下如何相册多图选择和删除,以及包括拍照功能,有需要的可以参考学习,下面来一起看看吧。

照例先上效果图

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

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

本次用的第三方框架为:qbimagepickercontroller

按照惯例,上代码,本次代码较多

第一个控制器 .h里没啥代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#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

?
1
2
3
4
5
6
7
8
#import <uikit/uikit.h>
#import "numberofwordstextview.h"
 
@interface rrzsendshowtextcell : uitableviewcell
 
@property (weak, nonatomic) numberofwordstextview *numbertextview;
 
@end

第二个控制器 .m

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#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能有一定的帮助,如果有疑问大家可以留言交流。

原文链接:http://www.jianshu.com/p/70738915e97b

延伸 · 阅读

精彩推荐
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17