iOS开发 UICollectionView无限拖拽排序功能实现

现在很多app功能点都非常多,如果将功能点都放在首页,这样就感觉比较乱,而且功能的主次也不容易区分,用户有些功能点是不需要经常操作的,像支付宝的功能点就非常多,因此支持用户自定义排序就非常有必要,笔者现在的项目功能点也非常之多,因此也支持用户自定义排序,用户可以自己选择在首页展示多少个功能,功能的顺序,用户也可以自己设置。这是项目的效果图:

屏幕快照 2017-09-23 09.46.13.png
屏幕快照 2017-09-23 09.46.24.png

其中首页只展示7个功能入口,其余的入口用户可以进入去全部里面查看,且所有功能入口可拖拽排序,用户可以根据自己的需要在首页展示自己常用的功能。下面就给出该功能的实现思路。
这种九宫格的东西利用collectionView实现最简单,对于iOS9.0以上系统,collectionView已支持拖拽排序,两个代理方法即可:

func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool 
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) 
iOS9以下系统的实现思路:

1.给cell添加长按手势

//
//  YRFunctionConfigCollectionViewCell.swift
//  YouRen
//
//  Created by MrZhaoCn on 2017/9/21.
//  Copyright © 2017年 Zhou Shaolin. All rights reserved.
//

import UIKit
protocol YRFunctionConfigCollectionViewCellDelegate:NSObjectProtocol {
    func configButtonClik(view:YRFunctionConfigCollectionViewCell,id:Int32)
    func dragCellGestureAction(gesture:UIGestureRecognizer,id:Int32)
}
class YRFunctionConfigCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet var configButton: UIButton!
    @IBOutlet var iconImageView: UIImageView!
    @IBOutlet var titleLabel: UILabel!
    @IBAction func configActionButtonClik(_ sender: Any) {
        guard let homeModel = homeModel else {
            return
        }
        delegate?.configButtonClik(view: self, id: homeModel.id)
    }
    weak var delegate:YRFunctionConfigCollectionViewCellDelegate?
    private var homeModel:YRHomeModuleModel?
    override func awakeFromNib() {
        super.awakeFromNib()
        //添加手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(gestureAction(gesture:)))
        self.addGestureRecognizer(longPress)
    }
    func gestureAction(gesture:UIGestureRecognizer) {
        guard let delegate = delegate else {
            return
        }
        guard let homeModel = homeModel else {
            return
        }
        delegate.dragSortCellGestureAction(gesture:gesture,id: homeModel.id)
    }
}

2.长按开始时截取cell视图,并将视图添加到collectionView上,并隐藏该cell

func dragCellGestureAction(gesture: UIGestureRecognizer,id:Int32) {
        //判断是哪个collectionView
        var collectionView:UICollectionView = deleteCollectionView
        for item in deleteHomeModels {
            if item.id == id {
                collectionView = deleteCollectionView
                break
            }
        }
        for item in addHomeModels {
            if item.id == id {
                collectionView = addCollectionView
                break
            }
        }
        let point = gesture.location(in: collectionView)
        switch gesture.state {
        case UIGestureRecognizerState.began:
            dragBegan(gesture:gesture,point: point,collectionView:collectionView)
        case UIGestureRecognizerState.changed:
            drageChang(gesture: gesture,point: point, collectionView: collectionView)
        case UIGestureRecognizerState.ended:
            drageEnd(point: point, collectionView: collectionView)
        default: break
        }
    }
//MARK: - 长按开始
func dragBegan(gesture: UIGestureRecognizer,point: CGPoint,collectionView:UICollectionView) {
        indexPath = collectionView.indexPathForItem(at: point)
        if indexPath == nil {
            return
        }
        let item = collectionView.cellForItem(at: indexPath!) as? YRFunctionConfigCollectionViewCell
       //截取视图
        self.snapItem = item?.snapshotView(afterScreenUpdates: true)
        self.snapItem?.center = (item?.center)!
        collectionView.addSubview(self.snapItem ?? UIView())
       //原cell隐藏
        item?.isHidden = true
        startPoint = gesture.location(in: collectionView)
    }

3.在拖拽过程中,根据手势的位置,不断调整截取视图的位置,交换数据源.

//MARK: - 长按过程
  func drageChang(gesture: UIGestureRecognizer,point: CGPoint,collectionView:UICollectionView) {
        if indexPath == nil {
            return
        }
        let tranX = gesture.location(ofTouch: 0, in: collectionView).x - startPoint.x
        let tranY = gesture.location(ofTouch: 0, in: collectionView).y - startPoint.y
        //设置截图视图位置
        self.snapItem?.center = __CGPointApplyAffineTransform((self.snapItem?.center)!, CGAffineTransform(translationX: tranX, y: tranY))
        startPoint = gesture.location(ofTouch: 0, in: collectionView)
        targetIndexPath = collectionView.indexPathForItem(at: point)
        if targetIndexPath == nil {
            return
        }
        // 更新数据
        if collectionView == deleteCollectionView {
            let obj = deleteHomeModels[indexPath!.item]
            deleteHomeModels.remove(at: indexPath!.item)
            deleteHomeModels.insert(obj, at: targetIndexPath!.item)
        } else {
            let obj = addHomeModels[indexPath!.item]
            addHomeModels.remove(at: indexPath!.item)
            addHomeModels.insert(obj, at: targetIndexPath!.item)
        }
        //交换位置
        collectionView.moveItem(at: indexPath!, to: targetIndexPath!)
        indexPath = targetIndexPath
    }

4.手势结束时获取手势的位置,并移除掉截取的视图即可。

//MARK: - 长按结束
   func drageEnd(point: CGPoint,collectionView:UICollectionView) {
        if indexPath == nil {
            return
        }
        let endCell = collectionView.cellForItem(at: indexPath!)
        UIView.animate(withDuration: 0.25, animations: 
            self.snapItem?.center = (endCell?.center)!
        }, completion: {
            (finish) -> () in
            endCell?.isHidden = false
            self.snapItem?.removeFromSuperview()
            self.indexPath = nil
        })
    }

注:笔者的项目要求上面的功能删除完时也要留有固定大小的区域同来添加功能,因此采用两个collectionView实现,但思路是一样的。其中deleteCollectionView为上面已添加的,deleteHomeModels为该数据源。addCollectionView为待添加的,addHomeModels为其数据源。

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

推荐阅读更多精彩内容