iOS UICollectionView删除图片

  • 仿造连接https://www.cnblogs.com/yang-guang-girl/p/7883117.html
iOS UICollectionView删除图片_第1张图片
效果
  • 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 ()

@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 *)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];
}

你可能感兴趣的:(iOS UICollectionView删除图片)