iOS開發(fā):UICollectionView長按移動、添加、刪除(仿支付寶首頁中的"全部"功能)

效果圖

UICollectionView添加手勢,可以使cell移動、添加、刪除,這種功能網(wǎng)上也有一大堆的資料可供查看,本文沒有做封裝,提供一個思路給讀者;封裝的再好,不符合自己的業(yè)務(wù),還是需要修改的;

仿支付寶的效果,你可以打開支付寶,首頁中有個全部功能,點擊進去,第一個分區(qū)的cell是可以移動,第一個分區(qū)可以添加,可以刪除;后面的分區(qū)不可以添加,也不能夠刪除和移動,如果第一個分區(qū)已經(jīng)有了,下面的就是一個??號,如果沒有,則顯示+號;第一個分區(qū)永遠都是-號,表示只能刪除;

首先創(chuàng)建一個繼承與UICollectionViewFlowLayout的類:.h中的代碼

#import <UIKit/UIKit.h>

@protocol SYLifeManagerDelegate <NSObject>

/**
 * 改變編輯狀態(tài)
 */
- (void)didChangeEditState:(BOOL)inEditState;

/**
 * 更新數(shù)據(jù)源
 */
- (void)moveItemAtIndexPath:(NSIndexPath *)formPath toIndexPath:(NSIndexPath *)toPath;

@end

@interface SYLifeManagerLayout : UICollectionViewFlowLayout

@property (nonatomic, assign) BOOL inEditState;
@property (nonatomic, assign) id<SYLifeManagerDelegate> delegate;

@end
.m中的代碼:
#import "SYLifeManagerLayout.h"
#import "SYLifeManagerCell.h"
#import "SYLifeManagerModel.h"
#import "Header.h"

@interface SYLifeManagerLayout ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) UILongPressGestureRecognizer *longGesture;
@property (nonatomic, strong) NSIndexPath *currentIndexPath; //當(dāng)前indexPath
@property (nonatomic, assign) CGPoint movePoint; //移動的中心點
@property (nonatomic, strong) UIView *moveView; //移動的視圖

@end

@implementation SYLifeManagerLayout

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self configureObserver];
    }
    return self;
}

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

#pragma mark - 添加觀察者

- (void)configureObserver
{
    [self addObserver:self forKeyPath:@"collectionView" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"collectionView"]) {
        [self setUpGestureRecognizers];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - 長按手勢

- (void)setUpGestureRecognizers
{
    if (self.collectionView == nil) {
        return;
    }
    [self.collectionView addGestureRecognizer:self.longGesture];
}

#pragma mark - 手勢動畫

- (void)longGesture:(UILongPressGestureRecognizer *)gesture
{
    if (!self.inEditState) {
        [self setInEditState:YES];
    }
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            CGPoint location = [gesture locationInView:self.collectionView];
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:location];
            //如果indexPath為空,不做任何操作
            if (indexPath == nil || indexPath.section != 0) return;
            self.currentIndexPath = indexPath;
            UICollectionViewCell *targetCell = [self.collectionView cellForItemAtIndexPath:self.currentIndexPath];
            //得到當(dāng)前cell的映射(截圖)
            self.moveView = [targetCell snapshotViewAfterScreenUpdates:YES];
            self.moveView.layer.borderWidth = 0.3;
            self.moveView.layer.borderColor = [UIColor sy_grayColor].CGColor;
            [self.collectionView addSubview:self.moveView];
            targetCell.hidden = YES;
            self.moveView.transform = CGAffineTransformMakeScale(1.1, 1.1);
            self.moveView.center = location;
        }
            break;
        case UIGestureRecognizerStateChanged: {
            CGPoint point = [gesture locationInView:self.collectionView];
            //更新cell的位置
            self.moveView.center = point;
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
            if (indexPath == nil)  return;
            if (indexPath.section == self.currentIndexPath.section && indexPath.section == 0) {
                [self.collectionView moveItemAtIndexPath:self.currentIndexPath toIndexPath:indexPath];
                //使用代理方法更新數(shù)據(jù)源
                if ([self.delegate respondsToSelector:@selector(moveItemAtIndexPath:toIndexPath:)]) {
                    [self.delegate moveItemAtIndexPath:self.currentIndexPath toIndexPath:indexPath];
                }
                self.currentIndexPath = indexPath;
            }
        }
            break;
        case UIGestureRecognizerStateEnded: {
            UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:self.currentIndexPath];
            [UIView animateWithDuration:0.25 animations:^{
                self.moveView.center = cell.center;
            } completion:^(BOOL finished) {
                [self.moveView removeFromSuperview];
                cell.hidden = NO;
                self.moveView = nil;
                self.currentIndexPath = nil;
                [self.collectionView reloadData];
            }];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 處于編輯狀態(tài)

- (void)setInEditState:(BOOL)inEditState
{
    if (_inEditState != inEditState) {
        if (_delegate && [_delegate respondsToSelector:@selector(didChangeEditState:)]) {
            [_delegate didChangeEditState:inEditState];
        }
    }
    _inEditState = inEditState;
}

#pragma mark - 移除觀察者

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"collectionView"];
}

#pragma mark - 手勢

- (UILongPressGestureRecognizer *)longGesture
{
    if (!_longGesture) {
        _longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGesture:)];
        _longGesture.minimumPressDuration = 0.5f; //時間長短
        _longGesture.delegate = self;
    }
    return _longGesture;
}

@end

限于文章篇幅長度,有需要的可以移步demo,demo里面有很多注釋,如果哪里有問題,可以交流;

SYLifeManagerCell創(chuàng)建的cell,這個就不用多講了,一般都是一張圖片和描述文案

SYLifeManagerModel創(chuàng)建的model

SYLifeManagerHeaderView是創(chuàng)建的區(qū)頭視圖,為了顯示分區(qū)標(biāo)題

SYLIfeManagerFooterView是區(qū)尾視圖,主要是為了實現(xiàn)分割線

Demo的Github地址,如果有問題或者好的建議,希望留言,歡迎交流!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,654評論 4 61
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,323評論 25 708
  • 關(guān)于閱讀的真相,略囧 羅輯思維為什么敗壞思維? 年輕人現(xiàn)在都如何看小說?我們發(fā)現(xiàn)這基本上是個 3 小時閱讀市場 這...
    沙加之倫閱讀 577評論 0 3
  • 買這本書的時間大概是2015年的2月份,那個時候考研成績還沒出,我也不想再看讓我頭大的專業(yè)書籍,就去某賣書的網(wǎng)址一...
    天舒閱讀 1,940評論 5 17
  • 01 今天出事業(yè)單位筆試的成績,心里上還是有點小緊張,第一次參加事業(yè)單位考試,難免如此。 看著單位網(wǎng)頁,不停的刷著...
    阿行PPT閱讀 3,089評論 0 1

友情鏈接更多精彩內(nèi)容