ios 仿相册-UICollectionVIew滑动多选实现

文件目录


截屏2023-05-11 15.44.00.png

效果图,绿色有序号的为选中的item


截屏2023-05-11 15.45.39.png

每个文件内容
viewController.m

#import "ViewController.h"
#import "MYCollectionViewCell.h"
#import "QYManager.h"
#import "MYModel.h"
#import "UIView+QYExtension.h"

static NSString *cellID = @"MYCollectionViewCell";
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width

@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property(nonatomic, strong) NSMutableArray *dataSource;
@property(nonatomic, strong) UICollectionView *myCollection;
@property (nonatomic, strong)UICollectionViewFlowLayout *layout;

// 手势
@property (assign, nonatomic) CGPoint panSelectStartPoint;
@property (assign, nonatomic) NSInteger currentPanSelectType;
@property (nonatomic, strong) QYManager *manager;
@property (strong, nonatomic) NSMutableArray *panSelectIndexPaths;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.myCollection];
    
    [self createDataSource];
    // 添加滑动手势
    UIPanGestureRecognizer *selectPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(selectPanGestureRecognizerClick:)];
    [self.view addGestureRecognizer:selectPanGesture];
}

- (void)createDataSource{
    NSMutableArray *muArray = [NSMutableArray array];
    NSArray *array = @[@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z"];
    for (int i = 0; i < array.count; i++) {
        MYModel *model = [[MYModel alloc] init];
        model.name = array[i];
        [muArray addObject:model];
    }
    self.dataSource = muArray;
    [self.myCollection reloadData];
}

- (NSMutableArray *)dataSource
{
    if(!_dataSource){
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

// 手势操作
- (void)selectPanGestureRecognizerClick:(UIPanGestureRecognizer *)panGesture {
        
    if (panGesture.state == UIGestureRecognizerStateBegan) {
        // 获取起始点
        self.panSelectStartPoint = [panGesture locationInView:self.myCollection];
        NSIndexPath *indexPath = [self.myCollection indexPathForItemAtPoint:self.panSelectStartPoint];
        if (indexPath) {
            // 起始点在cell上
            MYModel *firstModel = self.dataSource[indexPath.item];
            self.currentPanSelectType = !firstModel.selected;

        }else {
            // 起始点不在cell上
            self.currentPanSelectType = -1;
        }
    }else if (panGesture.state == UIGestureRecognizerStateChanged) {
        
        CGPoint currentPoint = [panGesture locationInView:self.myCollection];
        NSInteger firstLine = 0;
        NSInteger lastLine = 0;
        NSIndexPath *firstIndexPath = [self.myCollection indexPathForItemAtPoint:self.panSelectStartPoint];
        if (!firstIndexPath) {
            // 起始点不在cell上直接不可滑动选择
            return;
        }
        NSIndexPath *lastIndexPath = [self.myCollection indexPathForItemAtPoint:currentPoint];
        if (!lastIndexPath) {
            return;
        }
        NSInteger rowCount = 3;
        if ((firstIndexPath.item + 1) % rowCount == 0) {
            firstLine = (firstIndexPath.item + 1) / rowCount;
        }else {
            firstLine = (firstIndexPath.item + 1) / rowCount + 1;
        }
        if ((lastIndexPath.item + 1) % rowCount == 0) {
            lastLine = (lastIndexPath.item + 1) / rowCount;
        }else {
            lastLine = (lastIndexPath.item + 1) / rowCount + 1;
        }
        NSMutableArray *indexPaths = [NSMutableArray array];
        CGFloat startX;
        CGFloat maxX;
        BOOL xReverse = NO;
        if (currentPoint.x > self.panSelectStartPoint.x) {
            // 向右
            maxX = [self panSelectGetMaxXWithPoint:currentPoint];
            startX = [self panSelectGetMinXWithPoint:self.panSelectStartPoint];
        }else {
            // 向左
            xReverse = YES;
            maxX = [self panSelectGetMaxXWithPoint:self.panSelectStartPoint];
            startX = [self panSelectGetMinXWithPoint:currentPoint];
        }
        CGFloat maxY;
        CGFloat startY;
        BOOL yReverse = NO;
        if (currentPoint.y > self.panSelectStartPoint.y) {
            // 向下
            maxY = [self panSelectGetMaxYWithPoint:currentPoint];
            startY = [self panSelectGetMinYWithPoint:self.panSelectStartPoint];
        }else {
            // 向上
            yReverse = YES;
            maxY = [self panSelectGetMaxYWithPoint:self.panSelectStartPoint];
            startY = [self panSelectGetMinYWithPoint:currentPoint];
        }
        NSInteger distanceW = self.layout.minimumInteritemSpacing + self.layout.itemSize.width;
        NSInteger distanceH = self.layout.minimumInteritemSpacing + self.layout.itemSize.height;
        BOOL canSelectVideo = YES;
        NSIndexPath *sIndexPath = [self.myCollection indexPathForItemAtPoint:self.panSelectStartPoint];
        if (sIndexPath && ![indexPaths containsObject:sIndexPath]) {
            [indexPaths addObject:sIndexPath];
        }
        
        while (yReverse ? maxY > startY : startY < maxY) {
            
            CGFloat tempStartX = startX;
            CGFloat tempMaxX = maxX;
            NSInteger currentLine = 0;
            NSIndexPath *currentIndexPath;
            if (yReverse) {
                currentIndexPath = [self.myCollection indexPathForItemAtPoint:CGPointMake(tempMaxX - 1, maxY - 1)];
            }else {
                currentIndexPath = [self.myCollection indexPathForItemAtPoint:CGPointMake(tempStartX + 1, startY + 1)];
            }
            if ((currentIndexPath.item + 1) % rowCount == 0) {
                currentLine = (currentIndexPath.item + 1) / rowCount;
            }else {
                currentLine = (currentIndexPath.item + 1) / rowCount + 1;
            }
            if (currentLine == firstLine) {
                if (lastLine != firstLine) {
                    if (yReverse) {
                        tempMaxX = [self panSelectGetMaxXWithPoint:self.panSelectStartPoint];
                        tempStartX = 2;
                    }else {
                        if (xReverse) {
                            tempStartX = [self panSelectGetMinXWithPoint:self.panSelectStartPoint];
                        }
                        tempMaxX = SCREEN_WIDTH - 2;
                    }
                }
            }else if (currentLine == lastLine) {
                if (yReverse) {
                    tempStartX = [self panSelectGetMinXWithPoint:currentPoint];
                    tempMaxX = SCREEN_WIDTH - 2;
                }else {
                    tempStartX = 2;
                    if (xReverse) {
                        tempMaxX = [self panSelectGetMaxXWithPoint:currentPoint];
                    }
                }
            }else if (currentLine != firstLine && currentLine != lastLine) {
                tempStartX = 2;
                tempMaxX = SCREEN_WIDTH - 2;
            }
            
            while (yReverse ? tempMaxX > tempStartX : tempStartX < tempMaxX) {
                NSIndexPath *indexPath;
                if (yReverse) {
                    indexPath = [self panSelectCurrentIndexPathWithPoint:CGPointMake(tempMaxX, maxY) indexPaths:indexPaths canSelectVideo:canSelectVideo];
                }else {
                    indexPath = [self panSelectCurrentIndexPathWithPoint:CGPointMake(tempStartX, startY) indexPaths:indexPaths canSelectVideo:canSelectVideo];
                }
                if (indexPath) {
                    [indexPaths addObject:indexPath];
                }
                if (yReverse) {
                    tempMaxX -= distanceW / 2;
                }else {
                    tempStartX += distanceW / 2;
                }
            }
            if (yReverse) {
                maxY -= distanceH / 2;
            }else {
                startY += distanceH / 2;
            }
        }
        
        NSIndexPath *eIndexPath = [self.myCollection indexPathForItemAtPoint:currentPoint];
        
        if (eIndexPath && ![indexPaths containsObject:eIndexPath]) {
           
            MYModel *model = self.dataSource[eIndexPath.item];
            
            if (self.currentPanSelectType == 0) {
                if (model.selected) {
                    [indexPaths addObject:eIndexPath];
                }
            }
            
            else if (self.currentPanSelectType == 1) {
                if (!model.selected) {
                    [indexPaths addObject:eIndexPath];

                }
            }
        }

        if (self.currentPanSelectType == -1) {
            NSIndexPath *firstIndexPath = indexPaths.firstObject;
        
            MYModel *firstModel = [[MYModel alloc] init];
            
            if (firstIndexPath) {
                
                firstModel = self.dataSource[firstIndexPath.item];
                self.currentPanSelectType = !firstModel.selected;
                
            }

        }
                
        for (NSIndexPath *indexPath in indexPaths) {
            
            MYModel *model = self.dataSource[indexPath.item];
            
            if (self.currentPanSelectType == 0) {
                // 取消选择
                if (model.selected) {
                    [self.manager beforeSelectedListdeletePhotoModel:model];
                }
            }
            
            else if (self.currentPanSelectType == 1) {
                // 选择
                if (!model.selected) {
                        [self.manager beforeSelectedListAddPhotoModel:model];

                }
            }
        }
         
        [self.myCollection reloadData];
        
    }else if (panGesture.state == UIGestureRecognizerStateEnded ||
              panGesture.state == UIGestureRecognizerStateCancelled) {
        self.panSelectIndexPaths = nil;
        self.currentPanSelectType = -1;
    }
    
}

- (CGFloat)panSelectGetMaxXWithPoint:(CGPoint)point {
    
    NSIndexPath *indexPath = [self.myCollection indexPathForItemAtPoint:point];
    UICollectionViewCell *cell = [self.myCollection cellForItemAtIndexPath:indexPath];
    return CGRectGetMaxX(cell.frame) - 2;
}

- (CGFloat)panSelectGetMinXWithPoint:(CGPoint)point {
    
    NSIndexPath *indexPath = [self.myCollection indexPathForItemAtPoint:point];
    UICollectionViewCell *cell = [self.myCollection cellForItemAtIndexPath:indexPath];
    return cell.qy_x + 2;
}

- (CGFloat)panSelectGetMaxYWithPoint:(CGPoint)point {
    
    NSIndexPath *indexPath = [self.myCollection indexPathForItemAtPoint:point];
    UICollectionViewCell *cell = [self.myCollection cellForItemAtIndexPath:indexPath];
    return CGRectGetMaxY(cell.frame) - 2;
}

- (CGFloat)panSelectGetMinYWithPoint:(CGPoint)point {
    
    NSIndexPath *indexPath = [self.myCollection indexPathForItemAtPoint:point];
    UICollectionViewCell *cell = [self.myCollection cellForItemAtIndexPath:indexPath];
    return cell.qy_y + 2;
}

- (NSIndexPath *)panSelectCurrentIndexPathWithPoint:(CGPoint)point indexPaths:(NSMutableArray *)indexPaths canSelectVideo:(BOOL)canSelectVideo {
    NSIndexPath *indexPath = [self.myCollection indexPathForItemAtPoint:point];
    if (indexPath && ![indexPaths containsObject:indexPath]) {
        
        return indexPath;
    }
    return nil;
}
- (QYManager *)manager {
    if (!_manager) {
        _manager = [[QYManager alloc] init];
    }
    return _manager;
}

- (NSMutableArray *)panSelectIndexPaths {
    if (!_panSelectIndexPaths) {
        _panSelectIndexPaths = [NSMutableArray array];
    }
    return _panSelectIndexPaths;
}

#pragma mark- Delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MYCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(([UIScreen mainScreen].bounds.size.width-40)/3.0, 80);
}


- (UICollectionView *)myCollection
{
    if(!_myCollection){
        _layout = [[UICollectionViewFlowLayout alloc]init];
        _layout.minimumLineSpacing = 10;
        _layout.minimumInteritemSpacing = 5;
        _layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        _layout.sectionHeadersPinToVisibleBounds = YES;
        
        _myCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:_layout];
        _myCollection.backgroundColor = [UIColor whiteColor];
        
        [_myCollection registerClass:[MYCollectionViewCell class] forCellWithReuseIdentifier:cellID];

        _myCollection.delegate = self;
        _myCollection.dataSource = self;
        _myCollection.showsVerticalScrollIndicator = NO;
    }
    return _myCollection;
}

@end

MYCollectionViewCell.h

#import <UIKit/UIKit.h>
#import "MYModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface MYCollectionViewCell : UICollectionViewCell

@property(nonatomic, strong) MYModel *model;

@property (strong, nonatomic) UIButton *selectBtn;


@end

NS_ASSUME_NONNULL_END

MYCollectionViewCell.m

#import "MYCollectionViewCell.h"

@interface MYCollectionViewCell()
@property(nonatomic, strong)UILabel *label;

@end

@implementation MYCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createCellUI];
    }
    return self;
}
-(void)createCellUI {
    
    self.contentView.backgroundColor = [UIColor grayColor];
    self.contentView.layer.cornerRadius = 10.0;
    self.contentView.layer.masksToBounds = YES;
    [self.contentView addSubview:self.label];
    [self.contentView addSubview:self.selectBtn];
}
- (void)setModel:(MYModel *)model
{
    self.label.text = model.name;
    [self.selectBtn setTitle:model.selectIndexStr forState:UIControlStateNormal];
}
- (UILabel *)label
{
    if(!_label){
        _label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 50, 22)];
        _label.textColor = [UIColor blueColor];
        _label.font = [UIFont systemFontOfSize:14];
    }
    return _label;
}
- (UIButton *)selectBtn {
    
    if (!_selectBtn) {
        _selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectBtn.backgroundColor = [UIColor greenColor];
        _selectBtn.frame = CGRectMake(50, 20, 30, 30);
        [_selectBtn setTitleColor:UIColor.blueColor forState:UIControlStateNormal];
        _selectBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        _selectBtn.layer.cornerRadius = 15;
        _selectBtn.layer.masksToBounds = YES;
    }
    return _selectBtn;
}
@end

QYManager

#import <Foundation/Foundation.h>
#import "MYModel.h"

NS_ASSUME_NONNULL_BEGIN

@interface QYManager : NSObject

@property (strong, nonatomic) NSMutableArray *selectedList;
//完成之前从已选数组中删除某个模型
- (void)beforeSelectedListdeletePhotoModel:(MYModel *)model;

//完成之前添加某个模型到已选数组中
- (void)beforeSelectedListAddPhotoModel:(MYModel *)model;

//完成之前选择的所有数组
- (NSArray *)selectedArray;

@end

NS_ASSUME_NONNULL_END

QYManager.m

#import "QYManager.h"

@implementation QYManager

- (void)beforeSelectedListdeletePhotoModel:(MYModel *)model {
    model.selected = NO;
    model.selectIndexStr = @"";
    model.selectedIndex = 0;
    [self.selectedList removeObject:model];
    
    int i = 0;
    for (MYModel *model in self.selectedList) {
        model.selectIndexStr = [NSString stringWithFormat:@"%d",i + 1];
        i++;
    }
}

- (void)beforeSelectedListAddPhotoModel:(MYModel *)model {

    [self.selectedList addObject:model];
    model.selected = YES;
    model.selectedIndex = [self.selectedList indexOfObject:model];
    model.selectIndexStr = [NSString stringWithFormat:@"%ld",model.selectedIndex  + 1];
}
- (NSArray *)selectedArray {
    return self.selectedList;
}
- (NSMutableArray *)selectedList {
    if (!_selectedList) {
        _selectedList = [NSMutableArray array];
    }
    return _selectedList;
}
@end

UIView+QYExtension.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIView (QYExtension)

@property (assign,  nonatomic) CGFloat qy_x;
@property (assign,  nonatomic) CGFloat qy_y;
@property (assign,  nonatomic) CGFloat qy_w;
@property (assign,  nonatomic) CGFloat qy_h;
@property (assign,  nonatomic) CGFloat qy_centerX;
@property (assign,  nonatomic) CGFloat qy_centerY;
@property (assign,  nonatomic) CGSize qy_size;
@property (assign,  nonatomic) CGPoint qy_origin;

@end

NS_ASSUME_NONNULL_END

UIView+QYExtension.m

#import "UIView+QYExtension.h"

@implementation UIView (QYExtension)

- (void)setQy_x:(CGFloat)qy_x
{
    CGRect frame = self.frame;
    frame.origin.x = qy_x;
    self.frame = frame;
}

- (CGFloat)qy_x
{
    return self.frame.origin.x;
}

- (void)setQy_y:(CGFloat)qy_y
{
    CGRect frame = self.frame;
    frame.origin.y = qy_y;
    self.frame = frame;
}

- (CGFloat)qy_y
{
    return self.frame.origin.y;
}

- (void)setQy_w:(CGFloat)qy_w
{
    CGRect frame = self.frame;
    frame.size.width = qy_w;
    self.frame = frame;
}

- (CGFloat)qy_w
{
    return self.frame.size.width;
}

- (void)setQy_h:(CGFloat)qy_h
{
    CGRect frame = self.frame;
    frame.size.height = qy_h;
    self.frame = frame;
}

- (CGFloat)qy_h
{
    return self.frame.size.height;
}

- (CGFloat)qy_centerX
{
    return self.center.x;
}

- (void)setQy_centerX:(CGFloat)qy_centerX {
    CGPoint center = self.center;
    center.x = qy_centerX;
    self.center = center;
}

- (CGFloat)qy_centerY
{
    return self.center.y;
}

- (void)setQy_centerY:(CGFloat)qy_centerY {
    CGPoint center = self.center;
    center.y = qy_centerY;
    self.center = center;
}

- (void)setQy_size:(CGSize)qy_size
{
    CGRect frame = self.frame;
    frame.size = qy_size;
    self.frame = frame;
}

- (CGSize)qy_size
{
    return self.frame.size;
}

- (void)setQy_origin:(CGPoint)qy_origin
{
    CGRect frame = self.frame;
    frame.origin = qy_origin;
    self.frame = frame;
}

- (CGPoint)qy_origin
{
    return self.frame.origin;
}
@end

MYModel.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface MYModel : NSObject

/// 是否选中
@property (assign, nonatomic) BOOL selected;

/// 选择的下标
@property (assign, nonatomic) NSInteger selectedIndex;

/// 模型所对应的选中下标
@property (copy, nonatomic) NSString * _Nullable selectIndexStr;

/// cell是否显示过
@property (assign, nonatomic) BOOL dateCellIsVisible;

// 测试用
@property (nonatomic, copy) NSString *name;


@end

NS_ASSUME_NONNULL_END

MYModel.m

#import "MYModel.h"

@implementation MYModel

- (void)setSelectIndexStr:(NSString *)selectIndexStr {
    _selectIndexStr = selectIndexStr;
    self.selectedIndex = selectIndexStr.integerValue - 1;
}

@end

复制上面所有的文件即可实现多选功能

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

推荐阅读更多精彩内容