查看: 582|回复: 0

[IOS开发教程] iOS 通过collectionView实现照片删除功能

发表于 2017-12-27 08:00:00

一,效果图。

二,工程图。

三,代码。

ViewController.h

  1. #import <UIKit/UIKit.h>
  2. @interface ViewController : UIViewController
  3. <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
  4. {
  5. UICollectionView *_collectionView;
  6. UIImagePickerController *_imagePicker;
  7. NSMutableArray *photos;
  8. NSMutableArray *dataArray;
  9. NSInteger deleteIndex;
  10. BOOL wobble;
  11. }
  12. @end
复制代码

ViewController.m

  1. //点击添加按钮的时候,停止删除。
  2. #import "ViewController.h"
  3. #import "photoCollectionViewCell.h"
  4. NSInteger const Photo = 8;
  5. @interface ViewController ()
  6. @end
  7. @implementation ViewController
  8. - (void)viewDidLoad {
  9. [super viewDidLoad];
  10. // Do any additional setup after loading the view, typically from a nib.
  11. //其布局很有意思,当你的cell设置大小后,一行多少个cell,由cell的宽度决定
  12. UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
  13. //设置cell的尺寸
  14. [flowLayout setItemSize:CGSizeMake(70, 70)];
  15. //设置其布局方向
  16. [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
  17. //设置其边界(上,左,下,右)
  18. flowLayout.sectionInset = UIEdgeInsetsMake(5,5,5,5);
  19. _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(10, 50, 320,85*2) collectionViewLayout:flowLayout];
  20. _collectionView.dataSource = self;
  21. _collectionView.delegate = self;
  22. _collectionView.backgroundColor = [UIColor redColor];
  23. [_collectionView registerClass:[photoCollectionViewCell class] forCellWithReuseIdentifier:@"photo"];
  24. [self.view addSubview:_collectionView];
  25. photos = [[NSMutableArray alloc ] init];
  26. dataArray = [[NSMutableArray alloc ] init];
  27. [dataArray addObject:[UIImage imageNamed:@"contract_addpic1"]];
  28. }
  29. //section
  30. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  31. {
  32. return 1;
  33. }
  34. //item个数
  35. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  36. {
  37. return dataArray.count;
  38. }
  39. -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  40. {
  41. NSLog(@"--indexPath.row--%ld",indexPath.row);
  42. NSLog(@"---indexpath.section--%ld",indexPath.section);
  43. photoCollectionViewCell *cell = (photoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"photo" forIndexPath:indexPath];
  44. cell.tag=indexPath.row;
  45. //图片
  46. cell.photoImage.image=dataArray[indexPath.row];
  47. // 删除按钮
  48. cell.deleteBtn.tag =indexPath.row;
  49. cell.deleteBtn.hidden=YES;
  50. [cell.deleteBtn addTarget:self action:@selector(doClickDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
  51. //增加按钮
  52. if (indexPath.row == dataArray.count -1) {
  53. cell.addBtn.hidden = NO;
  54. }else
  55. {
  56. cell.addBtn.hidden = YES;
  57. }
  58. [cell.addBtn addTarget:self action:@selector(doClickAddButton:) forControlEvents:UIControlEventTouchUpInside];
  59. // 长按删除
  60. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc ] initWithTarget:self action:@selector(longPressedAction)];
  61. [cell.contentView addGestureRecognizer:longPress];
  62. return cell;
  63. }
  64. #pragma -mark -doClickActions
  65. //删除按钮
  66. -(void)doClickDeleteButton:(UIButton *)btn
  67. {
  68. NSLog(@"-----doClickDeleteButton-------");
  69. UIAlertView *alert = [[UIAlertView alloc ] initWithTitle:@"提示" message:@"您确定要删除吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
  70. deleteIndex = btn.tag;
  71. [alert show];
  72. NSLog(@"---delete--dataArray---%@",dataArray);
  73. }
  74. //增加按钮
  75. -(void)doClickAddButton:(UIButton *)btn
  76. {
  77. NSLog(@"-----doClickAddButton-------");
  78. if (wobble) {
  79. // 如果是编辑状态则取消编辑状态
  80. [self cancelWobble];
  81. }else{
  82. //不是编辑状态,添加图片
  83. if (dataArray.count > Photo) {
  84. UIAlertView *alert = [[UIAlertView alloc ] initWithTitle:@"提示" message:@"最多支持8个" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
  85. [alert show];
  86. }else
  87. {
  88. UIActionSheet *actionSheet = [[UIActionSheet alloc]
  89. initWithTitle:nil
  90. delegate:(id)self
  91. cancelButtonTitle:@"取消"
  92. destructiveButtonTitle:nil
  93. otherButtonTitles:@"拍照", @"我的相册",nil];
  94. actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
  95. [actionSheet showInView:self.view];
  96. }
  97. }
  98. NSLog(@"---add--dataArray---%@",dataArray);
  99. }
  100. //长按删除
  101. -(void)longPressedAction
  102. {
  103. NSLog(@"-----longPressedAction-------");
  104. wobble = YES;
  105. NSArray *array = [_collectionView subviews];
  106. for (int i = 0; i < array.count; i ++) {
  107. if ([array[i] isKindOfClass:[photoCollectionViewCell class]]) {
  108. photoCollectionViewCell *cell = array[i];
  109. if (cell.addBtn.hidden) {
  110. cell.deleteBtn.hidden = NO;
  111. }
  112. else
  113. {
  114. cell.deleteBtn.hidden = YES;
  115. cell.photoImage.image = [UIImage imageNamed:@"ensure"];
  116. cell.tag = 999999;
  117. }
  118. // 晃动动画
  119. [self animationViewCell:cell];
  120. }
  121. }
  122. }
  123. // 取消晃动
  124. -(void)cancelWobble
  125. {
  126. wobble = NO;
  127. NSArray *array = [_collectionView subviews];
  128. for (int i = 0; i < array.count; i ++) {
  129. if ([array[i] isKindOfClass:[photoCollectionViewCell class]]) {
  130. photoCollectionViewCell *cell = array[i];
  131. cell.deleteBtn.hidden = YES;
  132. if (cell.tag == 999999) {
  133. cell.photoImage.image = [UIImage imageNamed:@"plus"];
  134. }
  135. // 晃动动画
  136. [self animationViewCell:cell];
  137. }
  138. }
  139. }
  140. // 晃动动画
  141. -(void)animationViewCell:(photoCollectionViewCell *)cell
  142. {
  143. //摇摆
  144. if (wobble){
  145. cell.transform = CGAffineTransformMakeRotation(-0.1);
  146. [UIView animateWithDuration:0.08
  147. delay:0.0
  148. options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveLinear
  149. animations:^{
  150. cell.transform = CGAffineTransformMakeRotation(0.1);
  151. } completion:nil];
  152. }
  153. else{
  154. [UIView animateWithDuration:0.25
  155. delay:0.0
  156. options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseOut
  157. animations:^{
  158. cell.transform = CGAffineTransformIdentity;
  159. } completion:nil];
  160. }
  161. }
  162. #pragma -mark -UIActionSheetDelegate
  163. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
  164. {
  165. if (buttonIndex == 0) {
  166. [self openCamera];
  167. }else if(buttonIndex == 1) {
  168. [self openPics];
  169. }
  170. }
  171. #pragma -mark -UIAlertViewDelegate
  172. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  173. {
  174. if (buttonIndex == 1) {
  175. [dataArray removeObjectAtIndex:deleteIndex];
  176. NSIndexPath *path = [NSIndexPath indexPathForRow:deleteIndex inSection:0];
  177. [_collectionView deleteItemsAtIndexPaths:@[path]];
  178. // 如果删除完,则取消编辑
  179. if (dataArray.count == 1) {
  180. [self cancelWobble];
  181. }
  182. // 没有删除完,执行晃动动画
  183. else
  184. {
  185. [self longPressedAction];
  186. }
  187. }
  188. }
  189. #pragma -mark -camera
  190. // 打开相机
  191. - (void)openCamera {
  192. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
  193. {
  194. if (_imagePicker == nil) {
  195. _imagePicker = [[UIImagePickerController alloc] init];
  196. }
  197. _imagePicker.delegate = (id)self;
  198. _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
  199. _imagePicker.showsCameraControls = YES;
  200. _imagePicker.allowsEditing = YES;
  201. [self.navigationController presentViewController:_imagePicker animated:YES completion:nil];
  202. }
  203. }
  204. // 打开相册
  205. - (void)openPics {
  206. if (_imagePicker == nil) {
  207. _imagePicker = [[UIImagePickerController alloc] init];
  208. }
  209. _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  210. _imagePicker.allowsEditing = YES;
  211. _imagePicker.delegate = (id)self;
  212. [self presentViewController:_imagePicker animated:YES completion:NULL];
  213. }
  214. // 选中照片
  215. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  216. NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
  217. [_imagePicker dismissViewControllerAnimated:YES completion:NULL];
  218. _imagePicker = nil;
  219. // 判断获取类型:图片
  220. if ([mediaType isEqualToString:@"public.image"]){
  221. UIImage *theImage = nil;
  222. // 判断,图片是否允许修改
  223. if ([picker allowsEditing]){
  224. //获取用户编辑之后的图像
  225. theImage = [info objectForKey:UIImagePickerControllerEditedImage];
  226. } else {
  227. // 照片的元数据参数
  228. theImage = [info objectForKey:UIImagePickerControllerOriginalImage] ;
  229. }
  230. [dataArray insertObject:theImage atIndex:0];
  231. NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
  232. [_collectionView insertItemsAtIndexPaths:@[path]];
  233. }
  234. }
  235. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  236. [picker dismissViewControllerAnimated:YES completion:NULL];
  237. }
  238. // 判断设备是否有摄像头
  239. - (BOOL) isCameraAvailable{
  240. return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
  241. }
  242. #pragma mark - 相册文件选取相关
  243. // 相册是否可用
  244. - (BOOL) isPhotoLibraryAvailable{
  245. return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
  246. }
  247. - (void)didReceiveMemoryWarning {
  248. [super didReceiveMemoryWarning];
  249. // Dispose of any resources that can be recreated.
  250. }
  251. @end
复制代码

photoCollectionViewCell.h

  1. #import <UIKit/UIKit.h>
  2. @interface photoCollectionViewCell : UICollectionViewCell
  3. @property (weak, nonatomic) IBOutlet UIButton *addBtn;
  4. @property (weak, nonatomic) IBOutlet UIImageView *photoImage;
  5. @property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
  6. @end
复制代码

photoCollectionViewCell.m

  1. #import "photoCollectionViewCell.h"
  2. @implementation photoCollectionViewCell
  3. - (id)initWithFrame:(CGRect)frame
  4. {
  5. self = [super initWithFrame:frame];
  6. if (self)
  7. {
  8. // 初始化时加载collectionCell.xib文件
  9. NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"photoCollectionViewCell" owner:self options:nil];
  10. // 如果路径不存在,return nil
  11. if (arrayOfViews.count < 1)
  12. {
  13. return nil;
  14. }
  15. // 如果xib中view不属于UICollectionViewCell类,return nil
  16. if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]])
  17. {
  18. return nil;
  19. }
  20. // 加载nib
  21. self = [arrayOfViews objectAtIndex:0];
  22. }
  23. return self;
  24. }
  25. - (void)awakeFromNib {
  26. // Initialization code
  27. }
  28. @end
复制代码

总结

以上所述是小编给大家介绍的iOS 通过collectionView实现照片删除功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对程序员之家网站的支持!



回复

使用道具 举报