swift 拖动collectionCell并改变其位置和数据位置

老规矩 先上图:
QQ20181010-151146-HD.gif

1.为cell添加长按手势

let tap = UILongPressGestureRecognizer(target: self, action: #selector(delectBtn(_:)))
tap.minimumPressDuration = 1
tap.numberOfTouchesRequired = 1
cell.addGestureRecognizer(tap)

2.为长按手势添加事件

@objc func delectBtn(_ sender: UILongPressGestureRecognizer) {
    switch sender.state {
    case .began:
       //取得要移动cell的索引
       let selectedCellIndex = collectionView.indexPathForItem(at: sender.location(in: collectionView))
        //开始移动
            collectionView.beginInteractiveMovementForItem(at: selectedCellIndex!)
    case .changed:
        //移动ing
        collectionView.updateInteractiveMovementTargetPosition(sender.location(in: collectionView))
    case .ended:
        //结束移动
        collectionView.endInteractiveMovement()
    default:
        //取消移动
        collectionView.cancelInteractiveMovement()
    }
    
}

3.处理移动后数据的改变

//sourceIndexPath.item移动前cell的索引
//destinationIndexPath.item移动后的索引
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let tempMybook = mybook[sourceIndexPath.item]
    mybook.remove(at: sourceIndexPath.item)
    mybook.insert(tempMybook, at: destinationIndexPath.item)
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,222评论 3 119
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,679评论 1 32
  • 症状: 小米到家以后,大概只有不到2天的时间是正常的[捂脸][捂脸]2天后,就开始有轻微的拉肚子症状,便软,不成...
    杯酒未消阅读 3,013评论 0 0
  • 我曾经告诫自己cp圈地自萌,不要脑补过度,打扰到人好好的朋友之谊,直到我看了三遍昨天的直播后,什么圈地自萌见鬼去吧...
    翻鋆覆露阅读 259评论 0 0
  • 2018年6月17日 星期天 晴 父爱像一本厚重的书,耐人寻味,父爱像一杯干醇的酒,回味无穷。父爱是一棵大树,即使...
    四年级一班杨凯雯妈妈阅读 214评论 0 2

友情链接更多精彩内容