iOS 拖拽排序?qū)崿F(xiàn)

老早之前說(shuō)要做這個(gè)蛇尚,主要是看了微博的一個(gè)轉(zhuǎn)發(fā),然后發(fā)現(xiàn)其實(shí)系統(tǒng)已經(jīng)有自帶的功能了匆笤。不管怎么樣,先寫(xiě)一下基于UIColloctionView的拖曳排序庶诡。

在iOS 9之前需要手動(dòng)截圖cell并進(jìn)行拖曳計(jì)算咆课,iOS 9之后存在兩個(gè)delegate方法

-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    id objc = [_arr objectAtIndex:sourceIndexPath.item];
    [_arr removeObject:objc];
    [_arr insertObject:objc atIndex:destinationIndexPath.item];
}

實(shí)現(xiàn)這兩個(gè)方法就能實(shí)現(xiàn)拖曳排序。一步步來(lái)喇澡。
首先新建一個(gè)UIColloctionViewCell的子類(lèi)

MoveCollectionViewCell.png
//
//  MoveCollectionViewCell.h
//  MJChangeItem
//
//  Created by 馬家俊 on 16/12/12.
//  Copyright ? 2016年 MJJ. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol MoveCollectionViewCellDelegate <NSObject>
- (void)GesturePressDelegate:(UIGestureRecognizer *)gestureRecognizer;
@end
@interface MoveCollectionViewCell : UICollectionViewCell
{
    __weak id<MoveCollectionViewCellDelegate>m_MoveCollectionViewCellDelegate;
}
@property (nonatomic, weak) id<MoveCollectionViewCellDelegate> p_MoveCollectionViewCellDelegate;
@property (nonatomic, strong) NSString* cellName;
@end

代碼中先定義一個(gè)代理MoveCollectionViewCellDelegate撩幽,代理中需要實(shí)現(xiàn)是cell的長(zhǎng)按與拖動(dòng)手勢(shì)箩艺,其中拖動(dòng)手勢(shì)只需要在iOS 9之前的系統(tǒng)中添加艺谆。
再添加了一個(gè)cellName的屬性拜英,待會(huì)來(lái)重寫(xiě)set方法
到.m文件中

//
//  MoveCollectionViewCell.m
//  MJChangeItem
//
//  Created by 馬家俊 on 16/12/12.
//  Copyright ? 2016年 MJJ. All rights reserved.
//

#import "MoveCollectionViewCell.h"

@interface MoveCollectionViewCell()<UIGestureRecognizerDelegate>
@property(nonatomic,strong) UILabel* nameLab;
@end
@implementation MoveCollectionViewCell
@synthesize p_MoveCollectionViewCellDelegate = m_MoveCollectionViewCellDelegate;
@synthesize nameLab;
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addGestureCell];
        [self addLab];
    }
    return self;
}

這段是定義個(gè)label,添加下delegate虫给,初始化下cell侠碧,沒(méi)啥好說(shuō)的。
實(shí)現(xiàn)下init中的兩個(gè)方法

//為cell添加手勢(shì)
-(void)addGestureCell
{
    UILongPressGestureRecognizer * longPress =[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(GesturePress:)];
    longPress.delegate = self;
    [self addGestureRecognizer:longPress];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] <9)
    {
        UIPanGestureRecognizer * panGes =[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(GesturePress:)];
        panGes.delegate = self;
        [self addGestureRecognizer:panGes];
    }
}
//為cell添加lab
-(void)addLab
{
    nameLab = [UILabel new];
    nameLab.font = [UIFont systemFontOfSize:12];
    nameLab.textColor = [UIColor grayColor];
    nameLab.layer.borderColor = [UIColor grayColor].CGColor;
    nameLab.layer.borderWidth = 1;
    nameLab.layer.cornerRadius = 5;
    nameLab.layer.masksToBounds = YES;
    nameLab.textAlignment = NSTextAlignmentCenter;
    [self addSubview:nameLab];
}

最后重寫(xiě)下set方法

-(void)setCellName:(NSString *)cellName
{
    _cellName = cellName;
    nameLab.text = cellName;
    nameLab.frame = CGRectMake(0, 0, self.frame.size.width - 5, self.frame.size.height - 5);
    nameLab.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
}

哦药蜻,還有手勢(shì)對(duì)應(yīng)的方法替饿,代理跳轉(zhuǎn)到vc中實(shí)現(xiàn)

- (void)GesturePress:(UIGestureRecognizer *)gestureRecognizer{
    
    if (m_MoveCollectionViewCellDelegate && [m_MoveCollectionViewCellDelegate respondsToSelector:@selector(GesturePressDelegate:)]) {
        [m_MoveCollectionViewCellDelegate GesturePressDelegate:gestureRecognizer];
    }
}

這是cell的全部代碼。踱卵。据过。妒挎。

接下來(lái)去vc中

所有vc中聲明的屬性

//
//  ViewController.m
//  MJChangeItem
//
//  Created by 馬家俊 on 16/12/12.
//  Copyright ? 2016年 MJJ. All rights reserved.
//

#import "ViewController.h"
#import "MoveCollectionViewCell.h"
#define K_MAIN_SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define K_MAIN_SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MoveCollectionViewCellDelegate>
@property(nonatomic,strong) UICollectionView* MJColloctionView;
@property(nonatomic,strong) NSMutableArray* arr;
//iOS9 及之后棄用以下屬性
@property(nonatomic,strong) UIView * shotView;
@property(nonatomic,strong) NSIndexPath * indexPath;
@property(nonatomic,strong) NSIndexPath * nextIndexPath;
@property(nonatomic,weak) MoveCollectionViewCell * originalCell;
@end

懶加載初始化個(gè)UICollectionView

#define kItemSpace      20

- (UICollectionView *)MJColloctionView
{
    if (!MJColloctionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((K_MAIN_SCREEN_WIDTH-(kItemSpace*8))/9, 30);
        MJColloctionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 44, K_MAIN_SCREEN_WIDTH, K_MAIN_SCREEN_HEIGHT-44) collectionViewLayout:layout];
        [MJColloctionView registerClass:[MoveCollectionViewCell class] forCellWithReuseIdentifier:@"MoveCollectionViewCell"];
        MJColloctionView.dataSource = self;
        MJColloctionView.delegate = self;
        MJColloctionView.backgroundColor = [UIColor whiteColor];
    }
    return MJColloctionView;
}

是線下UIColloction代理

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _arr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MoveCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MoveCollectionViewCell" forIndexPath:indexPath];
    
    cell.p_MoveCollectionViewCellDelegate = self;
    cell.cellName = [_arr objectAtIndex:indexPath.row];
    return cell;
}
-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    id objc = [_arr objectAtIndex:sourceIndexPath.item];
    [_arr removeObject:objc];
    [_arr insertObject:objc atIndex:destinationIndexPath.item];
}

這樣至少能夠顯示出來(lái)colloctionview了;
最后要實(shí)現(xiàn)的就是拖曳這一個(gè)動(dòng)作了

-(void)GesturePressDelegate:(UIGestureRecognizer *)gestureRecognizer
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >9) {
        switch (gestureRecognizer.state) {
            case UIGestureRecognizerStateBegan:{
                //判斷手勢(shì)落點(diǎn)位置是否在路徑上
                NSIndexPath *indexPath = [MJColloctionView indexPathForItemAtPoint:[gestureRecognizer locationInView:self.MJColloctionView]];
                if (indexPath == nil) {
                    break;
                }
                //在路徑上則開(kāi)始移動(dòng)該路徑上的cell
                [MJColloctionView beginInteractiveMovementForItemAtIndexPath:indexPath];
            }
                break;
            case UIGestureRecognizerStateChanged:
                //移動(dòng)過(guò)程當(dāng)中隨時(shí)更新cell位置
                [MJColloctionView updateInteractiveMovementTargetPosition:[gestureRecognizer locationInView:self.MJColloctionView]];
                break;
            case UIGestureRecognizerStateEnded:
                //移動(dòng)結(jié)束后關(guān)閉cell移動(dòng)
                [MJColloctionView endInteractiveMovement];
                break;
            default:
                [MJColloctionView cancelInteractiveMovement];
                break;
        }

    }else
    {
        MoveCollectionViewCell* cell = (MoveCollectionViewCell*)gestureRecognizer.view;
        static CGPoint startPoint;
        if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
            _shotView = [cell snapshotViewAfterScreenUpdates:NO];
            _shotView.center = cell.center;
            
            NSLog(@"%@",cell.description);
            NSLog(@"%@",_shotView.description);
            [MJColloctionView addSubview:_shotView];
            _indexPath = [MJColloctionView indexPathForCell:cell];
            _originalCell = cell;
            _originalCell.hidden = YES;
            startPoint = [gestureRecognizer locationInView:MJColloctionView];
        }else if (gestureRecognizer.state == UIGestureRecognizerStateChanged)
        {
            //獲取移動(dòng)量
            CGFloat tranX = [gestureRecognizer locationOfTouch:0 inView:MJColloctionView].x - startPoint.x;
            CGFloat tranY = [gestureRecognizer locationOfTouch:0 inView:MJColloctionView].y - startPoint.y;
            
            //進(jìn)行移動(dòng)
            _shotView.center = CGPointApplyAffineTransform(_shotView.center, CGAffineTransformMakeTranslation(tranX, tranY));
            //更新初始位置
            startPoint = [gestureRecognizer locationOfTouch:0 inView:MJColloctionView];
            for (UICollectionViewCell *cellVisible in [MJColloctionView visibleCells])
            {
                //移動(dòng)的截圖與目標(biāo)cell的center直線距離
                CGFloat space = sqrtf(pow(_shotView.center.x - cellVisible.center.x, 2) + powf(_shotView.center.y - cellVisible.center.y, 2));
                //判斷是否替換位置庸队,通過(guò)直接距離與重合程度
                if (space <= _shotView.frame.size.width/2&&(fabs(_shotView.center.y-cellVisible.center.y) <= _shotView.bounds.size.height/2)) {
                    _nextIndexPath = [MJColloctionView indexPathForCell:cellVisible];
                    if (_nextIndexPath.item > _indexPath.item)
                    {
                        for(NSInteger i = _indexPath.item; i <_nextIndexPath.item;i++)
                        {
                            //移動(dòng)數(shù)據(jù)源位置
                            [_arr exchangeObjectAtIndex:i withObjectAtIndex:i+1];
                        }
                    }else
                    {
                        for(NSInteger i = _indexPath.item; i <_nextIndexPath.item;i--)
                        {
                            //移動(dòng)數(shù)據(jù)源位置
                            [_arr exchangeObjectAtIndex:i withObjectAtIndex:i-1];
                        }
                    }
                    //移動(dòng)視圖cell位置
                    [MJColloctionView moveItemAtIndexPath:_indexPath toIndexPath:_nextIndexPath];
                    //更新移動(dòng)視圖的數(shù)據(jù)
                    _indexPath = _nextIndexPath;
                    break;
                }
            }
        }else if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
        {
            [_shotView removeFromSuperview];
            [_originalCell setHidden:NO];
        }

    }
}

viewDidLoad加下數(shù)據(jù)

- (void)viewDidLoad {
    [super viewDidLoad];
    _arr = [[NSMutableArray alloc]initWithArray:[NSArray arrayWithObjects:@"我",@"的",@"背",@"脊",@"如",@"荒",@"丘",@",",@"而",@"你",@"卻",@"微",@"笑",@"擺",@"手",@",",@"把",@"它",@"當(dāng)",@"成",@"整",@"個(gè)",@"宇",@"宙", nil]];
    [self.view addSubview:self.MJColloctionView];
    // Do any additional setup after loading the view, typically from a nib.
}
2016-12-14 10_44_44.gif

就醬..................QAQ

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市宙拉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌煌贴,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件牛郑,死亡現(xiàn)場(chǎng)離奇詭異敬鬓,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)础芍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)数尿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人右蹦,你說(shuō)我怎么就攤上這事∧凼担” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,764評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵宰缤,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我朦乏,道長(zhǎng),這世上最難降的妖魔是什么呻疹? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,193評(píng)論 1 292
  • 正文 為了忘掉前任筹陵,我火速辦了婚禮,結(jié)果婚禮上朦佩,老公的妹妹穿的比我還像新娘。我一直安慰自己宋彼,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布输涕。 她就那樣靜靜地躺著慨畸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪先口。 梳的紋絲不亂的頭發(fā)上碉京,一...
    開(kāi)封第一講書(shū)人閱讀 51,182評(píng)論 1 299
  • 那天螟深,我揣著相機(jī)與錄音,去河邊找鬼界弧。 笑死,一個(gè)胖子當(dāng)著我的面吹牛垢箕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播忠荞,決...
    沈念sama閱讀 40,063評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼堂油!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起府框,我...
    開(kāi)封第一講書(shū)人閱讀 38,917評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤讥邻,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后计维,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,329評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蜈首,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評(píng)論 2 332
  • 正文 我和宋清朗相戀三年欠母,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赏淌。...
    茶點(diǎn)故事閱讀 39,722評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖六水,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情掷贾,我是刑警寧澤,帶...
    沈念sama閱讀 35,425評(píng)論 5 343
  • 正文 年R本政府宣布场靴,位于F島的核電站,受9級(jí)特大地震影響旨剥,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜轨帜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評(píng)論 3 326
  • 文/蒙蒙 一衩椒、第九天 我趴在偏房一處隱蔽的房頂上張望蚕礼。 院中可真熱鬧梢什,春花似錦、人聲如沸嗡午。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,671評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至宵距,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間满哪,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,825評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工哨鸭, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留娇妓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,729評(píng)論 2 368
  • 正文 我出身青樓哈恰,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親着绷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容