使用collectionView实现添加删除相册或拍照图片的效果,并且可以点击查看添加的图片,可以放大查看的图片
下列方法中用到infoChooseView的是自定义的选择视图,可以将其替换成UIAlterViewController
picCollectionView
#import <UIKit/UIKit.h>
#import "PicCollectionViewCell.h"
#import "ZoomImageScrollView.h"
#import "infoChooseView.h"
#import "InfoAcquisitionModel.h"
#import "infoRecordView.h"
@protocol PicCollectionViewDelegate<NSObject>
@optional
//- (void)openAlbum;//选择相册
//
//- (void)openCamera;//选择拍照
- (void)changeViewHeight:(NSInteger)row;//动态改变mainView高度
@required
- (void)showChooseView;//展示选择视图
- (void)removePicture:(NSInteger)tag;//传tag给父视图,以删除对应数据
@end
@interface PicCollectionView : UIView<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
ZoomImageScrollView *zoomImageView;
NSString *pushImageName;//待加入照片名
UILabel *addImageStrLabel; //添加图片提示
}
@property (nonatomic,weak)id<PicCollectionViewDelegate>delegate;
@property (nonatomic,strong)infoChooseView *chooseView;//选择视图
@property (nonatomic,strong)infoRecordView *recordView;//录音视图
@property (nonatomic,strong)UICollectionViewLayout *customLayout;
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *imageArray;//照片数组
@property (nonatomic,strong)NSMutableArray *dataArray;//数据数组,用于判断数据类型
-(void)addImage:(UIImage *)image;
@end
#import "PicCollectionView.h"
#define COLLECTION_VIEW_WiDTH SCREEN_WIDTH * 0.9
@implementation PicCollectionView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupView];
}
return self;
}
- (void)setupView
{
[self loadCollectionView];
}
//创建collectionView
- (void)loadCollectionView
{
float labelX = (IS_IPAD)?SCREEN_HEIGHT * 0.2:SCREEN_HEIGHT * 0.15;
if(_imageArray.count == 0)
{
_imageArray = [NSMutableArray array];
}
if (_dataArray.count == 0) {
_dataArray = [NSMutableArray array];
}
pushImageName = @"plus.png";
// cell的布局方式,默认流水布局(UICollectionViewFlowLayout)
_customLayout = [[UICollectionViewFlowLayout alloc] init];
// 设置滚动方式为水平,默认是垂直滚动
// [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
// 初始化UICollectionView
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.9,SCREEN_HEIGHT * 0.1) collectionViewLayout:_customLayout];
_collectionView.allowsSelection = NO;
// _collectionView.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1];
_collectionView.backgroundColor = [UIColor whiteColor];
// 注册cell,此处的Identifier和DataSource方法中的Identifier保持一致,cell只能通过注册来确定重用标识符
[_collectionView registerClass:[PicCollectionViewCell class] forCellWithReuseIdentifier:@"myCell"];
_collectionView.delegate = self;
_collectionView.dataSource = self;
[self addSubview:_collectionView];
//上传图片提示
addImageStrLabel = [[UILabel alloc]init];
addImageStrLabel.text = @"请添加踏勘内容";
addImageStrLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
[_collectionView addSubview:addImageStrLabel];
[addImageStrLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(200, 20));
make.left.mas_equalTo(labelX);
make.centerY.mas_equalTo(_collectionView.centerY).offset(0);
}];
}
#pragma mark - UICollectionView DataSource
// section数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
// section内行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _imageArray.count + 1;
}
// 每个cell的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
return CGSizeMake(SCREEN_HEIGHT * 0.09,SCREEN_HEIGHT * 0.09);
}
垂直间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
// return SCREEN_HEIGHT * 0.025;
//}
//
水平间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
// return (COLLECTION_VIEW_WiDTH - SCREEN_HEIGHT * 0.36 - SCREEN_HEIGHT * 0.24)/3.0;
//}
// 设置每个cell上下左右相距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(SCREEN_HEIGHT * 0.005, (COLLECTION_VIEW_WiDTH - SCREEN_HEIGHT * 0.36)/4.0, SCREEN_HEIGHT * 0.005, (COLLECTION_VIEW_WiDTH - SCREEN_HEIGHT * 0.36)/4.0);
}
// cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
PicCollectionViewCell *cell = (PicCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
if (indexPath.row == _imageArray.count) {
[cell.profilePhoto setImage:[UIImage imageNamed:pushImageName]];
cell.closeButton.hidden = YES;
//没有任何图片
if (_imageArray.count == 0) {
addImageStrLabel.hidden = NO;
}
else{
addImageStrLabel.hidden = YES;
}
}
else{
[cell.profilePhoto setImage:_imageArray[indexPath.item]];
cell.closeButton.hidden = NO;
}
[cell setBigImageViewWithImage:nil];
cell.profilePhoto.tag = [indexPath item] + 20000;
//添加图片cell点击事件
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
singleTap.numberOfTapsRequired = 1;
cell.profilePhoto .userInteractionEnabled = YES;
[cell.profilePhoto addGestureRecognizer:singleTap];
cell.closeButton.tag = [indexPath item] + 20000;
[cell.closeButton addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];
[self changeCollectionViewHeight];
return cell;
}
#pragma mark - UICollectionView Delegate
#pragma mark - 图片cell点击事件
//点击图片看大图
- (void) tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer{
UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
NSInteger index = tableGridImage.tag - 20000;
if (index == (_imageArray.count)) {
//添加新图片
// [self addNewImage];
if(_imageArray.count < 9)
{
[self.delegate showChooseView];
}else{
[University_Util showAlert:@"最多添加9条信息"];
}
}
else{
InfoAcquisitionModel *model = [[InfoAcquisitionModel alloc]init];
model = _dataArray[index];
if ([model.type isEqualToString:@"1"]) {
//点击放大查看
PicCollectionViewCell *cell = (PicCollectionViewCell*)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
if (!cell.BigImageView || !cell.BigImageView.image) {
[cell setBigImageViewWithImage:[_imageArray objectAtIndex:index]];
}
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
[tap addTarget:self action:@selector(closeImageBtnClick)];
[UIView animateWithDuration:0.5 animations:^{
//zoomImage
zoomImageView = [[ZoomImageScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
[zoomImageView setBackgroundColor:[UIColor grayColor]];
zoomImageView.imageView.contentMode = UIViewContentModeScaleAspectFit;
[zoomImageView addGestureRecognizer:tap];
[zoomImageView.imageView setImage:cell.BigImageView.image];
[[self viewController].view addSubview:zoomImageView];
}];
}else
{
_recordView = [[infoRecordView alloc]init];
[_recordView playRecord:model.path view:[self viewController].view];
}
}
}
#pragma mark - 选择图片
- (void)addNewImage
{
if (!_chooseView) {
_chooseView = [[infoChooseView alloc]initWithFrame:[UIScreen mainScreen].bounds];
[[self viewController].view addSubview:_chooseView];
}
}
#pragma mark - 删除照片
- (void)deletePhoto:(UIButton *)sender{
[_imageArray removeObjectAtIndex:sender.tag - 20000];
//传参数给父视图
[self.delegate removePicture:sender.tag - 20000];
[self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:(sender.tag - 20000) inSection:0]]];
for (NSInteger item = sender.tag - 20000; item <= _imageArray.count; item++) {
PicCollectionViewCell *cell = (PicCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
cell.closeButton.tag--;
cell.profilePhoto.tag--;
}
[self changeCollectionViewHeight];
}
#pragma mark - 改变view,collectionView高度
- (void)changeCollectionViewHeight{
NSInteger col_count = (IS_IPAD)?5:4;
self.collectionView.size = CGSizeMake(COLLECTION_VIEW_WiDTH,SCREEN_HEIGHT * 0.1 * ((int)_imageArray.count/col_count +1)+SCREEN_HEIGHT * 0.005);
//启动代理
NSInteger row = (int)_imageArray.count/col_count +1;
[self.delegate changeViewHeight:row];
}
- (void)closeImageBtnClick
{
[UIView animateWithDuration:0.5 animations:^{
[zoomImageView removeFromSuperview];
}];
}
//添加图片
-(void)addImage:(UIImage *)image
{
[self.imageArray addObject:image];
[self.collectionView reloadData];
}
//寻找当前view的VC
- (UIViewController *)viewController {
for (UIView* next = [self superview]; next; next = next.superview) {
UIResponder *nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
}
return nil;
}
@end
picCollectionViewCell
#import <UIKit/UIKit.h>
@interface PicCollectionViewCell : UICollectionViewCell
@property (strong, nonatomic) UIImageView *profilePhoto;
@property (strong, nonatomic) UIButton *closeButton;
@property(nonatomic,strong) UIImageView *BigImageView;
/** 查看大图 */
- (void)setBigImageViewWithImage:(UIImage *)image;
@end
#import "PicCollectionViewCell.h"
@implementation PicCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self imageViewInit];
[self closeBtnInit];
}
return self;
}
- (UIImageView *)imageViewInit
{
if (!_profilePhoto) {
_profilePhoto = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, self.frame.size.width - 5, self.frame.size.height - 5)];
// [_profilePhoto setBackgroundColor:MF_ColorFromRGBA2(0xf1f2f3, 1)];
[self addSubview:_profilePhoto];
}
return _profilePhoto;
}
- (UIButton *)closeBtnInit
{
if (!_closeButton) {
_closeButton = [[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width - 20, 0, 20, 20)];
// [_closeButton setBackgroundColor:[UIColor redColor]];
[_closeButton setBackgroundImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
[self addSubview:_closeButton];
}
return _closeButton;
}
- (void)setBigImageViewWithImage:(UIImage *)image
{
if (_BigImageView) {
//如果大图正在显示,还原小图
_BigImageView.frame = _profilePhoto.frame;
_BigImageView.image = image;
}else{
_BigImageView = [[UIImageView alloc] initWithImage:image];
_BigImageView.frame = _profilePhoto.frame;
[self insertSubview:_BigImageView atIndex:0];
}
_BigImageView.contentMode = UIViewContentModeScaleToFill;
}
@end
zoomImageScrollView
#import <UIKit/UIKit.h>
@interface ZoomImageScrollView : UIScrollView<UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
BOOL flag;
}
@property (nonatomic, strong) UIImageView *imageView;
@end
#import "ZoomImageScrollView.h"
#define MRScreenWidth CGRectGetWidth([UIScreen mainScreen].applicationFrame)
#define MRScreenHeight CGRectGetHeight([UIScreen mainScreen].applicationFrame)
@interface ZoomImageScrollView (Utility)
- (CGRect)zoomRectForScale:(CGFloat)scale withCenter:(CGPoint)center;
@end
@implementation ZoomImageScrollView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.delegate = self;
self.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
flag = NO;
[self initImageView];
}
return self;
}
- (void)initImageView
{
_imageView = [[UIImageView alloc]init];
// [imageView setBackgroundColor:[UIColor blueColor]];
// [self setBackgroundColor:[UIColor yellowColor]];
// The imageView can be zoomed largest size
_imageView.frame = CGRectMake(0, 0, self.frame.size.width * 2.5, self.frame.size.height * 2.5);
_imageView.userInteractionEnabled = YES;
[self addSubview:_imageView];
// Add gesture,double tap zoom imageView.
UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleDoubleTap:)];
[doubleTapGesture setNumberOfTapsRequired:2];
[doubleTapGesture setNumberOfTouchesRequired:1];
doubleTapGesture.delegate = self;
//[_imageView addGestureRecognizer:doubleTapGesture];
CGFloat minimumScale = self.frame.size.width / _imageView.frame.size.width;
[self setMinimumZoomScale:minimumScale];
[self setZoomScale:minimumScale];
}
#pragma mark - Zoom methods
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture
{
if (flag==NO) {
_imageView.contentMode = UIViewContentModeCenter;
flag=YES;
if (_imageView.image.size.height>0) {
_imageView.frame =CGRectMake(0, 0, _imageView.image.size.width*self.zoomScale, _imageView.image.size.height*self.zoomScale);
}
}else{
_imageView.contentMode = UIViewContentModeScaleAspectFit;
_imageView.frame = CGRectMake(0, 0, self.frame.size.width * 2.5*self.zoomScale, self.frame.size.height * 2.5*self.zoomScale);
flag=NO;
}
CGFloat scrollViewHeight = 0.0f;
CGFloat scrollViewWidth = 0.0f;
for (UIView* view in self.subviews){
scrollViewHeight += view.frame.size.height;
scrollViewWidth +=view.frame.size.width;
}
// [self setContentSize:(CGSizeMake(scrollViewWidth*(1-self.zoomScale), scrollViewHeight*(1-self.zoomScale)))];
CGRect zoomRect = [self zoomRectForScale:(1-self.zoomScale) withCenter:[gesture locationInView:gesture.view]];
[self zoomToRect:zoomRect animated:YES];
// [imageView setCenter:CGPointMake((self.contentSize.width-imageView.frame.size.width)/2+imageView.frame.size.width, (self.contentSize.height-imageView.frame.size.height)/2+imageView.frame.size.height)];
// [self setContentOffset:CGPointMake(self.contentSize.width/2, MRScreenHeight/2)];
}
- (CGRect)zoomRectForScale:(CGFloat)scale withCenter:(CGPoint)center
{
if (0 == scale) {
scale = 0.1;
}
CGRect zoomRect;
zoomRect.size.height = self.frame.size.height / scale;
zoomRect.size.width = self.frame.size.width / scale;
zoomRect.origin.x = zoomRect.size.width*2.5/2 - (zoomRect.size.width / 2.0);
zoomRect.origin.y = self.frame.size.height*2.5/2 - (zoomRect.size.height / 2.0);
NSLog(@"--%lf,%lf",center.x,center.y);
return zoomRect;
}
#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return _imageView;
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
[scrollView setZoomScale:scale animated:NO];
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
CGFloat offsetX = (self.bounds.size.width > self.contentSize.width)?(self.bounds.size.width - self.contentSize.width) * 0.5 : 0.0;
CGFloat offsetY = ((self.bounds.size.height) > self.contentSize.height)?((self.bounds.size.height) - self.contentSize.height) * 0.5 : 0.0;
// self.center = CGPointMake(self.contentSize.width * 0.5 + offsetX,self.contentSize.height * 0.5 + offsetY);
_imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
scrollView.contentSize.height * 0.5 + offsetY);
}
@end