摘要: 直接copy代码运行就可以了,图片自己去找
//
// XMHFlowLayout.h
// 自定义CollectionViewFlowLayout
//
// Created by 徐茂怀 on 16/6/1.
// Copyright © 2016年 徐茂怀. All rights reserved.
//
#import <UIKit/UIKit.h>
@class XMHFlowLayout;
@protocol XMHFlowLayoutDelegate <NSObject>
/**
* 这个代理方法用于在viewcontroller中通过Width来计算高度
*
* @param Flow flowlayout
* @param width 图片的宽
* @param indexPath indexPath
*
* @return 图片的高
*/
-(CGFloat)Flow:(XMHFlowLayout *)Flow heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath*)indexPath;
@end
@interface XMHFlowLayout : UICollectionViewFlowLayout
@property(nonatomic,assign)UIEdgeInsets sectionInset;
@property(nonatomic,assign)CGFloat rowMagrin;//行间距
@property(nonatomic,assign)CGFloat colMagrin;//列间距
@property(nonatomic,assign)CGFloat colCount;//多少列
@property(nonatomic,weak)id<XMHFlowLayoutDelegate>degelate;
@end
//
// XMHFlowLayout.m
// 自定义CollectionViewFlowLayout
//
// Created by 徐茂怀 on 16/6/1.
// Copyright © 2016年 徐茂怀. All rights reserved.
//
#import "XMHFlowLayout.h"
@interface XMHFlowLayout ()
@property(nonatomic,retain)NSMutableDictionary * maxYdic;
@property (nonatomic, strong) NSIndexPath *pinchedItem;
@property (nonatomic) CGSize pinchedItemSize;
@end
@implementation XMHFlowLayout
-(NSMutableDictionary *)maxYdic
{
if (!_maxYdic) {
self.maxYdic = [[NSMutableDictionary alloc] init];
}
return _maxYdic;
}
-(instancetype)init
{
if (self=[super init]) {
self.colMagrin = 10;
self.rowMagrin = 10;
self.sectionInset = UIEdgeInsetsMake(40, 10, 10, 10);
self.colCount = 2;
}
return self;
}
-(void)prepareLayout
{
[super prepareLayout];
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
-(CGSize)collectionViewContentSize
{
__block NSString * maxCol = @"0";
//找出最长的列
[self.maxYdic enumerateKeysAndObjectsUsingBlock:^(NSString * column, NSNumber *maxY, BOOL *stop) {
if ([maxY floatValue]>[self.maxYdic[maxCol] floatValue]) {
maxCol = column;
}
}];
return CGSizeMake(0, [self.maxYdic[maxCol] floatValue]);
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
__block NSString * minCol = @"0";
//找出最短的列
[self.maxYdic enumerateKeysAndObjectsUsingBlock:^(NSString * column, NSNumber *maxY, BOOL *stop) {
if ([maxY floatValue]<[self.maxYdic[minCol] floatValue]) {
minCol = column;
}
}];
// 计算宽度
CGFloat width = (self.collectionView.frame.size.width-self.sectionInset.left-self.sectionInset.right-(self.colCount - 1)*self.colMagrin)/self.colCount;
// 计算高度
CGFloat hight = [self.degelate Flow:self heightForWidth:width atIndexPath:indexPath ];
CGFloat x = self.sectionInset.left + (width + self.colMagrin)* [minCol intValue];
CGFloat y =[self.maxYdic[minCol] floatValue]+self.rowMagrin;
// 将之前的字典里每列对应得y的值加上高度,跟新每列最大的y值
self.maxYdic[minCol] = @(y+hight);
// 计算位置
UICollectionViewLayoutAttributes * attri =[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attri.frame = CGRectMake(x, y, width, hight);
return attri;
}
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
for(int i = 0;i<self.colCount;i++)
{
NSString * col = [NSString stringWithFormat:@"%d",i];
self.maxYdic[col] = @0;
}
NSMutableArray * array = [NSMutableArray array];
NSInteger count = [self.collectionView numberOfItemsInSection:0];
for (int i = 0; i < count; i++) {
UICollectionViewLayoutAttributes * attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
[array addObject:attrs];
}
return array;
}
@end
//
// ViewController.m
// 图片
//
// Created by ST on 16/6/12.
// Copyright © 2016年 ST. All rights reserved.
//
#import "ViewController.h"
#import "CustomViewCell.h"
#import "XMHFlowLayout.h"
#define screenWidth [UIScreen mainScreen].bounds.size.width
#define screenHeight [UIScreen mainScreen].bounds.size.height
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,XMHFlowLayoutDelegate,CustomViewCellDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIActionSheetDelegate,UIAlertViewDelegate>{
UICollectionView *_collectionView;
NSMutableArray *imageData;
}
@end
static NSString *cellID = @"cellid";
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
imageData = [[NSMutableArray alloc]init];
for (int i=1; i<9; i++) {
[imageData addObject:[NSString stringWithFormat:@"%d.jpg",i]];
}
[imageData addObject:@"add.png"];
[self initCollectView];
}
- (void)initCollectView{
XMHFlowLayout *layout= [[XMHFlowLayout alloc]init];
layout.degelate = self;
layout.colMagrin = (screenWidth-300)/3;
layout.colCount = 3;
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
_collectionView.backgroundColor = [UIColor whiteColor];
_collectionView.dataSource = self;
_collectionView.delegate = self;
[self.view addSubview:_collectionView];
// 注册cell、sectionHeader、sectionFooter
[_collectionView registerClass:[CustomViewCell class] forCellWithReuseIdentifier:cellID];
}
- (void)deleteImage:(CustomViewCell *)cell{
NSIndexPath *index = [_collectionView indexPathForCell:cell];
[imageData removeObjectAtIndex:index.row];
[_collectionView reloadData];
}
-(CGFloat)Flow:(XMHFlowLayout *)Flow heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath*)indexPath{
return 100;
}
//设置每个item的大小,双数的为50*50 单数的为100*100
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
// return CGSizeMake(80, 80);
//}
//代理相应方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
if (imageData.count>9) {
return 9;
}
return imageData.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CustomViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
cell.delegate = self;
UIImage *addImage = nil;
if ([imageData[indexPath.row] isKindOfClass:[NSString class]]) {
addImage = [UIImage imageNamed:imageData[indexPath.row]];
}
else if([imageData[indexPath.row] isKindOfClass:[UIImage class]])
{
addImage = imageData[indexPath.row];
}
cell.imageV.image = addImage;
if (indexPath.row == imageData.count - 1){
cell.deleteBtn.hidden = YES;
}else{
cell.deleteBtn.hidden = NO;
}
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == imageData.count - 1){
[self callImagePicker];
}
}
// 调用图片选择器
- (void)callImagePicker{
[self.view endEditing:YES];
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择图片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从手机相册选择", nil];
[sheet showInView:self.view];
}
#pragma mark - actionSheet的协议方法 ----- 继续上传图片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
UIImagePickerController *ipVC = [[UIImagePickerController alloc] init];
ipVC.delegate = self;
ipVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
ipVC.allowsEditing = YES;
if (buttonIndex == 0) {
BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
if (isCamera) {
ipVC.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentViewController:ipVC animated:YES completion:nil];
}else if(buttonIndex==1){
ipVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:ipVC animated:YES completion:nil];
}else{
}
}
#pragma mark - UIImagePickerController 代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// UIImage *image = info[UIImagePickerControllerEditedImage];
//对获取的图片进行一些处理
UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
// NSData *data_image = UIImageJPEGRepresentation(image, 0.00001);
[imageData insertObject:image atIndex:imageData.count-1];
[_collectionView reloadData];
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
//
// CustomViewCell.h
// 图片
//
// Created by ST on 16/6/12.
// Copyright © 2016年 ST. All rights reserved.
//
#import <UIKit/UIKit.h>
@class CustomViewCell;
@protocol CustomViewCellDelegate <NSObject>
- (void)deleteImage:(CustomViewCell *)cell;
@end
@interface CustomViewCell : UICollectionViewCell
@property (nonatomic, strong) UIButton *deleteBtn;; //
@property (nonatomic, strong) UIImageView *imageV;; //
@property (nonatomic, assign) id<CustomViewCellDelegate>delegate; //
@end
//
// CustomViewCell.m
// 图片
//
// Created by ST on 16/6/12.
// Copyright © 2016年 ST. All rights reserved.
//
#import "CustomViewCell.h"
@implementation CustomViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self initView];
}
return self;
}
- (void)initView{
_imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
[self.contentView addSubview:_imageV];
//
_deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_deleteBtn.frame = CGRectMake(0, 0, 30, 30);
[_deleteBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
[_deleteBtn setBackgroundImage:[UIImage imageNamed:@"deletbutton.png"] forState:UIControlStateNormal];
[self.contentView addSubview:_deleteBtn];
}
- (void)commitBtnClick{
if (self.delegate&&[self.delegate respondsToSelector:@selector(deleteImage:)]) {
[self.delegate deleteImage:self];
}
}
@end