模仿微信九宫格、查看大图

由于项目需要封装了一个九宫格显示图片,查看大图、选择多张图片、可以设置图片的最大数量、一排最大值、上下左右边距、图片的横向 纵向间距、默认图片、删除图标。话不多说先上图

Demo地址 [项目链接地址](https://github.com/xiangxianxiao/PicturesListData)


```
//
//  ViewController.m
//  PicturesListData
//
//  Created by Mac on 2018/10/10.
//  Copyright © 2018年 xiangxx. All rights reserved.
//

#import "ViewController.h"
#import "XXPicturesCollection.h"
#import "XXImageBrowseViewController.h"

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    XXPicturesCollection *pictures;
}

@property (nonatomic, strong) NSMutableArray *addPicturesData;

@property (weak, nonatomic) IBOutlet XXPicturesCollection *addPicturesView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    self.addPicturesData = [[NSMutableArray alloc] initWithCapacity:0];

    pictures = [[XXPicturesCollection alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 500)];
    pictures.configuration.maxRow = 4;
    pictures.configuration.maxValue = 6;

    pictures.configuration.addImageName = [UIImage imageNamed:@"community_photo"];
    pictures.configuration.deleteImageName = [UIImage imageNamed:@"community_close"];

    [self.view addSubview:pictures];

    __weak typeof(self)weakSelf = self;
    pictures.configuration.selectBlock = ^(NSMutableArray *arrayPictures, NSInteger status) {
        if (status == -1) {
            //添加图片
            weakSelf.addPicturesData = arrayPictures;
            [weakSelf photoLibraychoosephoto];
        }else{
            //点击放大第几个图片
            XXImageBrowseViewController *imageBro = [[XXImageBrowseViewController alloc] init];
            imageBro.imageUrlStringArray =  arrayPictures;
            imageBro.currentIndex = status;
            [weakSelf.navigationController pushViewController:imageBro animated:NO];
        }
    };

    
//    self.addPicturesView.configuration.addImageName = [UIImage imageNamed:@"community_photo"];
//    self.addPicturesView.configuration.deleteImageName = [UIImage imageNamed:@"community_close"];
//
//    self.addPicturesView.configuration.maxRow = 4;
//    self.addPicturesView.configuration.maxValue = 5;
//    __weak typeof(self)weakSelf = self;
//    self.addPicturesView.configuration.selectBlock = ^(NSMutableArray *arrayPictures, NSInteger status) {
//        if (status == -1) { //添加图片
//            weakSelf.addPicturesData = arrayPictures;
//            [weakSelf photoLibraychoosephoto];
//        }else{ //点击放大第几个图片
//            //点击放大第几个图片
//            XXImageBrowseViewController *imageBro = [[XXImageBrowseViewController alloc] init];
//            imageBro.imageUrlStringArray =  arrayPictures;
//            imageBro.currentIndex = status;
//            [weakSelf.navigationController pushViewController:imageBro animated:NO];
//        }
//    };
    
}


#pragma mark 调用相册 获取图片
-(void)photoLibraychoosephoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing =  YES;
    picker.navigationBar.translucent = NO;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片
    
    [self.addPicturesData insertObject:image atIndex:0];
//    self.addPicturesView.imageArray = self.addPicturesData;
    pictures.imageArray = self.addPicturesData;
}

//当用户取消选择的时候,调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

```

```
//
//  XXPicturesCollection.h
//  PicturesListData
//
//  Created by Mac on 2018/10/10.
//  Copyright © 2018年 xiangxx. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 选择进行处理操作

 @param arrayPictures 相册数组数据
 @param status 0 添加 1相片放大
 */
typedef void(^SelectPicturesBlock)(NSMutableArray *arrayPictures,NSInteger status);
@class XXPicturesCollection;
@interface XXPicturesCollectionConfiguration : NSObject

@property (nonatomic, copy) SelectPicturesBlock selectBlock;

/**
 图片最大值
 */
@property (nonatomic, assign) NSInteger maxValue;


/**
 一排最大值
 */
@property (nonatomic, assign) NSInteger maxRow;


/**
 边距的间距 上边 左边 下边 右边
 */
@property (nonatomic, assign) NSInteger topMargin;
@property (nonatomic, assign) NSInteger leftMargin;
@property (nonatomic, assign) NSInteger bottomMargin;
@property (nonatomic, assign) NSInteger rightMargin;


/**
 图片横向间距
 */
@property (nonatomic, assign) NSInteger horizontalSpacing;

/**
 图片竖向间距
 */
@property (nonatomic, assign) NSInteger verticalSpacing;


/**
 相关视图
 */
@property (nonatomic, strong) XXPicturesCollection * picturesCollection;

/**
 添加事件的图片
 */
@property (nonatomic, strong) UIImage *addImageName;


/**
 删除事件的图片
 */
@property (nonatomic, strong) UIImage *deleteImageName;

@end

@interface XXPicturesCollection : UIView

/**
 初始化

 @param frame 位置
 @param configuration 配置
 @return 图片添加器
 */
- (instancetype)initWithFrame:(CGRect)frame AndConfiguration:(XXPicturesCollectionConfiguration *)configuration;

/**
 配置
 */
@property (nonatomic, strong) XXPicturesCollectionConfiguration * configuration;

@property (nonatomic, strong) NSMutableArray *imageArray;

@end

```

//
//  XXPicturesCollection.m
//  PicturesListData
//
//  Created by Mac on 2018/10/10.
//  Copyright © 2018年 xiangxx. All rights reserved.
//

#import "XXPicturesCollection.h"
#import "XXPicturesCollectionViewCell.h"

@implementation XXPicturesCollectionConfiguration

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initData];
    }
    return self;
}

- (void)initData{
    
    self.maxValue = 9;
    self.maxRow = 3;
    
    self.topMargin = 10;
    self.leftMargin = 10;
    self.bottomMargin = 10;
    self.rightMargin = 10;
    
    self.horizontalSpacing = 8;
    self.verticalSpacing = 8;

    self.addImageName = [UIImage imageNamed:@"community_photo"];
    self.deleteImageName = [UIImage imageNamed:@"community_close"];
    
}

- (void)setMaxRow:(NSInteger)maxRow {
    _maxRow = maxRow;
    self.picturesCollection.configuration = self;
}

- (void)setMaxValue:(NSInteger)maxValue{
    _maxValue = maxValue;
    self.picturesCollection.configuration = self;
}

- (void)setTopMargin:(NSInteger)topMargin{
    _topMargin = topMargin;
    self.picturesCollection.configuration = self;
}

- (void)setLeftMargin:(NSInteger)leftMargin{
    _leftMargin = leftMargin;
    self.picturesCollection.configuration = self;
}

- (void)setBottomMargin:(NSInteger)bottomMargin{
    _bottomMargin = bottomMargin;
    self.picturesCollection.configuration = self;
}

- (void)setRightMargin:(NSInteger)rightMargin{
    _rightMargin = rightMargin;
    self.picturesCollection.configuration = self;
}

- (void)setHorizontalSpacing:(NSInteger)horizontalSpacing{
    _horizontalSpacing = horizontalSpacing;
    self.picturesCollection.configuration = self;
}

- (void)setVerticalSpacing:(NSInteger)verticalSpacing{
    _verticalSpacing = verticalSpacing;
    self.picturesCollection.configuration = self;
}

- (void)setaddImageName:(UIImage *)addImageName{
    _addImageName = addImageName;
    self.picturesCollection.configuration = self;
}

- (void)setDeleteImageName:(UIImage *)deleteImageName{
    _deleteImageName = deleteImageName;
    self.picturesCollection.configuration = self;
}

@end

@interface XXPicturesCollection()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, assign) CGFloat width;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *picturesArray;

@property (nonatomic, assign) NSInteger indexTag;

@end

@implementation XXPicturesCollection

- (instancetype)initWithFrame:(CGRect)frame AndConfiguration:(XXPicturesCollectionConfiguration *)configuration {
    if (self = [super initWithFrame:frame]) {
        self.configuration = configuration;
        self.configuration.picturesCollection = self;
        [self initUI];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.configuration = [[XXPicturesCollectionConfiguration alloc] init];
        self.configuration.picturesCollection = self;
//        [self initUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.configuration = [[XXPicturesCollectionConfiguration alloc] init];
        self.configuration.picturesCollection = self;
//        [self initUI];
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.configuration = [[XXPicturesCollectionConfiguration alloc] init];
        self.configuration.picturesCollection = self;
        
    }
    return self;
}

#pragma mark - layoutSubviews
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _width =  self.frame.size.width;
    if (!self.collectionView) {
        [self initUI];
    }else {
        self.collectionView.frame = CGRectMake(0, 0, _width, self.frame.size.height);
    }
    
}

- (void)setConfiguration:(XXPicturesCollectionConfiguration *)configuration {
    _configuration = configuration;
    [self.collectionView reloadData];
}

- (void)initUI{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, _width, self.frame.size.height) collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.collectionView];
    
    [self.collectionView registerClass:[XXPicturesCollectionViewCell class] forCellWithReuseIdentifier:@"XXPicturesCollectionViewCell"];
    
    self.picturesArray = [NSMutableArray arrayWithObjects:@"", nil];
    self.imageArray = [[NSMutableArray alloc] init];
}

- (void)setImageArray:(NSMutableArray *)imageArray{
    _imageArray = imageArray;
    if (imageArray.count > 0) {
        _picturesArray = _imageArray;
        [self.collectionView reloadData];
    }
}

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

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (self.picturesArray.count < _configuration.maxValue) {
        return self.picturesArray.count;
    }
    return _configuration.maxValue;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XXPicturesCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XXPicturesCollectionViewCell" forIndexPath:indexPath];
    
    [cell.deleteImage setBackgroundImage:self.configuration.deleteImageName forState:UIControlStateNormal];
    [cell.deleteImage addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteImage.tag = 10000 + indexPath.row;
    
    if (self.picturesArray.count-1 != self.configuration.maxValue) {
        
        if (self.picturesArray.count -1 == indexPath.row) {
            
            cell.deleteImage.hidden = YES;
            
            self.indexTag = indexPath.row;
            
            cell.imageView.image = self.configuration.addImageName;
            [cell.deleteImage setBackgroundImage:self.configuration.deleteImageName forState:UIControlStateNormal];
        
        }else{
            cell.deleteImage.hidden = NO;
            [cell.imageView setImage:self.picturesArray[indexPath.row]];
        }
    }else if(self.picturesArray.count-1 == self.configuration.maxValue){
        cell.deleteImage.hidden = NO;
        [cell.imageView setImage:self.picturesArray[indexPath.row]];
        self.indexTag = self.configuration.maxValue;
    }
    return cell;
}

- (void)deleteAction:(UIButton *)btn{
    
    NSInteger btnTag = btn.tag - 10000;
    if (self.picturesArray.count > 1) {
        [self.picturesArray removeObjectAtIndex:btnTag];
        [self.collectionView reloadData];
    }
}

#pragma mark  定义每个UICollectionView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat widthCollection = (_width - ((_configuration.maxRow-1) * _configuration.horizontalSpacing + _configuration.rightMargin + _configuration.leftMargin))/_configuration.maxRow;
    return  CGSizeMake(widthCollection, widthCollection);
}

#pragma mark  定义整个CollectionViewCell与整个View的间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(_configuration.topMargin, _configuration.leftMargin, _configuration.bottomMargin, _configuration.rightMargin);
}


#pragma mark  定义每个UICollectionView的横向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return _configuration.horizontalSpacing;
}

#pragma mark  定义每个UICollectionView的纵向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return _configuration.verticalSpacing;
}

#pragma mark  点击CollectionView触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    if (self.indexTag == indexPath.row) {// 相册选择图片
        
        if (self.configuration.selectBlock) {
            self.configuration.selectBlock(self.picturesArray, -1);
        }
    }else{ // 放大第几个图片
        if (self.configuration.selectBlock) {
            self.configuration.selectBlock(self.picturesArray, indexPath.row);
        }
    }
}

#pragma mark  设置CollectionViewCell是否可以被点击
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


//#pragma mark - 添加长按手势
//- (void)setUpLongPressGes {
//    UILongPressGestureRecognizer *longPresssGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
//    [self.collectionView addGestureRecognizer:longPresssGes];
//}

@end

```
#import <UIKit/UIKit.h>

@interface XXPicturesCollectionViewCell : UICollectionViewCell


/**
 显示的图片
 */
@property (nonatomic, strong) UIImageView *imageView;


/**
 删除图片
 */
@property (nonatomic, strong) UIButton *deleteImage;

@end
```

```
#import "XXPicturesCollectionViewCell.h"

@implementation XXPicturesCollectionViewCell


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.imageView];
        [self.contentView addSubview:self.deleteImage];
    }
    return self;
}

- (UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.frame = self.bounds;
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
    }
    return _imageView;
}

- (UIButton *)deleteImage{
    if (!_deleteImage) {
        _deleteImage = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteImage.frame = CGRectMake(_imageView.frame.size.width-10, -5, 15, 15);
    }
    return _deleteImage;
}

@end

```

```
/**
 点击查看图片
 */
@interface XXImageBrowseViewController : UIViewController

@property (strong, nonatomic) NSArray *imageUrlStringArray;

@property (nonatomic, copy) NSString *isNetWork;

@property (nonatomic, assign) NSInteger currentIndex;

@end

```

```
#import "XXImageBrowseViewController.h"

#import "EZImageBrowser.h"
#import "EZImageBrowserCell.h"
#import <EZImageBrowserKit/EZImageBrowserKit.h>
#import "UIImageView+WebCache.h"

@interface XXImageBrowseViewController ()<EZImageBrowserDelegate>


@end

@implementation XXImageBrowseViewController

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    EZImageBrowser *browser = [[EZImageBrowser alloc] init];
    [browser setDelegate:self];
    [browser showWithCurrentIndex:_currentIndex completion:nil];
    
}

#pragma mark - EZImageBrowserDelegate
- (NSInteger)numberOfCellsInImageBrowser:(EZImageBrowser *)imageBrowser{
    return self.imageUrlStringArray.count - 1; // 减去最后的加号图片
}

- (EZImageBrowserCell *)imageBrowser:(EZImageBrowser *)imageBrowser cellForRowAtIndex:(NSInteger )index{
   
        EZImageBrowserCell *cell = [imageBrowser dequeueReusableCell];
        if (!cell) {
            cell = [[EZImageBrowserCell alloc] init];
        }
    
        if (self.isNetWork){
            cell.loadingView.hidden = YES;
            [cell.imageView sd_setImageWithURL:[[NSURL alloc] initWithString:self.imageUrlStringArray[index]] placeholderImage:[UIImage imageNamed:@"post_info_z"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                CGFloat progress = (CGFloat)receivedSize / expectedSize;
                [cell.loadingView showAnimateByPropress:progress];
            } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                cell.loadingView.hidden = YES;
            }];
        }else{
            cell.imageView.image = self.imageUrlStringArray[index];
        }
        return cell;
}

//- (void)imageBrowserWillDisappear:(EZImageBrowser *)imageBrowser{
//    
//}

-(void)imageBrowserDidDisappear:(EZImageBrowser *)imageBrowser{
    [self.navigationController popViewControllerAnimated:NO];
}

@end
```
#图片浏览器
    pod 'EZImageBrowserKit'
    pod 'SDWebImage'


Demo地址 [项目链接地址](https://github.com/xiangxianxiao/PicturesListData)

猜你喜欢

转载自blog.csdn.net/u011043997/article/details/83178389