iOS UICollectionView删除图片

效果
  • PhotoViewCell
@interface PhotoViewCell : UICollectionViewCell

@property(nonatomic,strong)UIImageView *photoImageView;
@property(nonatomic,strong)UIButton *delBtn;

@end
@implementation PhotoViewCell

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.contentView.backgroundColor = [UIColor blueColor];
        
        _photoImageView = [[UIImageView alloc] init];
        [self.contentView addSubview:_photoImageView];
        
        _delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _delBtn.hidden = YES;
        [_delBtn setBackgroundImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        [self.contentView addSubview:_delBtn];
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    _photoImageView.frame = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
    _delBtn.frame = CGRectMake(self.frame.size.width - 10.0f, -10.0f, 20.0f, 20.0f);

}

// 删除按钮超出区域响应
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    CGPoint tempPoint = [_delBtn convertPoint:point fromView:self];
    if ([_delBtn pointInside:tempPoint withEvent:event]) {
        return _delBtn;
    }
    return view;
}
  • ViewController
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong)UICollectionViewFlowLayout *layout;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UIImagePickerController *imagePickerController;

@property(nonatomic,copy)NSArray *data;
@property(nonatomic,copy)NSMutableArray *tempArray;
@property(nonatomic,assign)NSInteger deleteIndex;
@property(nonatomic,assign)BOOL edit; // 编辑状态

@end
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _edit = NO;
    
    [self tempArray];
    [self data];
    
    
    [self imagePickerController];
    [self layout];
    [self collectionView];
    [_collectionView registerClass:[PhotoViewCell class] forCellWithReuseIdentifier:@"PhotoCellIdentifier"];
    
}
  • 懒加载
#pragma mark - lazy method
-(NSMutableArray *)tempArray
{
    if (!_tempArray) {
        _tempArray = [[NSMutableArray alloc] init];
    }
    return _tempArray;
}

-(NSArray *)data
{
    if (!_data) {
        [_tempArray addObject:[UIImage imageNamed:@"add"]];
        _data = [_tempArray mutableCopy];
        [_tempArray removeAllObjects];
    }
    return _data;
}

-(UICollectionViewFlowLayout *)layout
{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.minimumLineSpacing = 10.0f; // item 纵间距
        _layout.minimumInteritemSpacing = 10.0f; // item之间 行间距
    }
    return _layout;
}

-(UICollectionView *)collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10.0f, 64.0f, self.view.frame.size.width - 20.0f,200.0f) collectionViewLayout:_layout];
        _collectionView.backgroundColor = [UIColor orangeColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

-(UIImagePickerController *)imagePickerController
{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
    }
    return _imagePickerController;
}
#pragma mark - UICollectionViewDelegateFlowLayout
// 每个item的宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(60.0f, 60.0f);
}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(15.0f, 15.0f, 15.0f, 15.0f);
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _data.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoViewCell *cell = (PhotoViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCellIdentifier" forIndexPath:indexPath];
    cell.tag = indexPath.row;
    
    cell.photoImageView.image = _data[indexPath.row];
    
    [cell.delBtn addTarget:self action:@selector(deleteClickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    if (indexPath.row == _data.count - 1) {
        // 长按删除
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc ] initWithTarget:self action:@selector(longPressedAction)];
        [cell.contentView addGestureRecognizer:longPress];
        
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_edit) {
        NSLog(@"indexPath - %ld",(long)indexPath.row);
    } else {
        if (indexPath.row == _data.count - 1) {
            [self openPhotoLibrary];
            //        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            //        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //            NSLog(@"取消");
            //        }];
            //        UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //            NSLog(@"相册");
            //        }];
            //        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //            NSLog(@"拍照");
            //        }];
            //        [alertController addAction:cancelAction];
            //        [alertController addAction:albumAction];
            //        [alertController addAction:photoAction];
            //        [self presentViewController:alertController animated:YES completion:nil];
        }
    }
    
}
// 打开相册
- (void)openPhotoLibrary
{
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    _imagePickerController.allowsEditing = YES;
    _imagePickerController.delegate = self;
    [self presentViewController:_imagePickerController animated:YES completion:NULL];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    [_imagePickerController dismissViewControllerAnimated:YES completion:NULL];
    // 判断获取类型:图片
    if ([mediaType isEqualToString:@"public.image"]){
        UIImage *theImage = nil;
        // 判断,图片是否允许修改
        if ([picker allowsEditing]){
            //获取用户编辑之后的图像
            theImage = [info objectForKey:UIImagePickerControllerEditedImage];
        } else {
            // 照片的元数据参数
            theImage = [info objectForKey:UIImagePickerControllerOriginalImage] ;
        }
        
        _tempArray = [_data mutableCopy];
        NSUInteger index = _tempArray.count - 1;
        [_tempArray insertObject:theImage atIndex:index];
        _data = [_tempArray mutableCopy];
        [_tempArray removeAllObjects];
        [_collectionView reloadData];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

//长按删除
-(void)longPressedAction
{
    if (_data.count != 1) {
        _edit = YES;
        NSArray *array = [_collectionView visibleCells];
        for (NSUInteger i = 0; i < array.count; i++) {
            PhotoViewCell *cell = array[i];
            if (cell.tag != (_data.count - 1)) {
                cell.delBtn.hidden = NO;
                // 晃动动画
                [self animationViewCell:cell];
            }
        }
    }
}

// 图片删除完成操作
-(void)cancelEdit
{
    _edit = NO;
    NSArray *array =  [_collectionView subviews];
    for (int i = 0; i < array.count; i ++) {
        if ([array[i] isKindOfClass:[PhotoViewCell class]]) {
            PhotoViewCell *cell = array[i];
            cell.delBtn.hidden =  YES;
            // 晃动动画
            [self animationViewCell:cell];
        }
    }
}

// 晃动动画
-(void)animationViewCell:(PhotoViewCell *)cell
{
    //摇摆
    if (_edit){
        cell.transform = CGAffineTransformMakeRotation(-0.1);
        [UIView animateWithDuration:0.8f delay:0.02f options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionCurveLinear animations:^{
            
            cell.transform = CGAffineTransformMakeRotation(0.1);
            
        } completion:NULL];
    } else {
        
        [UIView animateWithDuration:0.25
                              delay:0.0
            options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseOut
                         animations:^{
                             cell.transform = CGAffineTransformIdentity;
                         } completion:nil];
    }
}


-(void)deleteClickAction:(UIButton *)button
{
    UIView *contentView = [button superview];
    PhotoViewCell *cell = (PhotoViewCell *)[contentView superview];
    NSIndexPath *indexPath = [_collectionView indexPathForCell:cell];
    
    _tempArray = [_data mutableCopy];
    [_tempArray removeObjectAtIndex:indexPath.row];
    _data = [_tempArray mutableCopy];
    [_tempArray removeAllObjects];
    
    [_collectionView reloadData];
    [self cancelEdit];
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,701评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,649评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,037评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,994评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,018评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,796评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,481评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,370评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,868评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,014评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,153评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,832评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,494评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,039评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,437评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,131评论 2 356

推荐阅读更多精彩内容

  • 今天,我逃避了半个月的问题再此提上日程。找工作。期间我给自己找了很多理由去逃避,比如做兼职丰富个人作品,学习要刻苦...
    夙沙诺阅读 133评论 0 1
  • 周末那就是小妞撒花庆祝的时间。 上午雷打不动的去舞蹈班跳舞,好不容易得了一个小胸牌奖励又被小妞给折腾没了。出来后的...
    鸽子000000阅读 186评论 0 0
  • (一)昨日总结 96天 昨天一大早起誓,要关机,然后开始了远离手机的生活。我认真学习,静心和自己相处。直到下午六点...
    青衣雨翼_shape阅读 397评论 0 0
  • 今天是搬入新教室的第二天,班里的孩子小轩变了,变得安稳了许多。 以前的小轩是个活跃小女生,在教室里安坐不了几分钟,...
    珊珊来迟_868e阅读 158评论 0 7