UIKit 在 UICollectionView 中拖放交换 Cell 视图的极简实现

在这里插入图片描述

概览

UIKit 中的 UICollectionView 视图是我们显示多列集合数据的不二选择,而丰富多彩的交互操作更是我们选择 UICollectionView 视图的另一个重要原因。

在这里插入图片描述

如上图所示:我们实现了在 UICollectionView 中拖放交换任意两个 Cell 子视图的功能,这是怎么做到的呢?

其实,完成这样一种交换远比小伙伴们想象的要简单的多!

所以,还等什么呢?Let‘s find out!!!😉


1. UICollectionView 拖放交互基本思路

在 iOS(iPadOS/MacOS) 中,广义的拖放操作涉及到跨越不同 App 间的范畴:比如,我们常常希望将微信中的图片直接拖动到 QQ 的聊天界面中去。

不过,这里我们只想在 App 内部进行拖动,所以完成起来就要简单许多。我们的数据元素不需要满足 NSItemProvider 或 NSSecureCoding 等一些苛刻限制,只是单纯的数据即可。

一般来说,为了完成拖放,我们需要在对应视图上实现 UIDragInteractionDelegate 和 UIDropInteractionDelegate 协议指定的方法。

而对于 UICollectionView 视图,其子 Cell 间的拖动我们还有更简单的方式:遵守 UICollectionViewDragDelegate 和 UICollectionViewDropDelegate 协议即可。

在这里插入图片描述

iOS(iPadOS/MacOS) 系统中关于拖放(Drag & Drop)更详细全面的介绍,苹果官网无疑是一个很好的选择:

2. 构建 storyboard

首先,新建一个 UIKit 项目,打开 Main 故事板(Main.storyboard)为视图控制器添加一个 UICollectionView 子视图:

在这里插入图片描述

如上图所示,我们随后又在 UICollectionView 中添加了一个静态的 UICollectionViewCell 控件:

在这里插入图片描述

然后,调整 UICollectionViewCell 背景以及 Label 字体大小和颜色到满意为止:

在这里插入图片描述

最后,妥善设置好 UICollectionViewCell 的 ID:

在这里插入图片描述

并将 UICollectionView 关联到视图控制器的 collectionView 属性上:

在这里插入图片描述

3. 准备数据源

现在界面布局已准备就绪,我们接下来需要创建数据模型:

struct Item {
   
    var id = UUID()
    var title: String
    
    static var preview: [Item] {
   
        [
            Item(title: "Apple"), Item(title: "Banana"),
            Item(title: "Cherry"), Item(title: "Date"),
            Item(title: "Dragon"), Item(title: "Sheep"),
            Item(title: "V-Malicious"), Item(title: "X-Code"),
            Item(title: "GreatWall"), Item(title: "TaiTan"),
            Item(title: "Milk"), Item(title: "🥸"),
        ]
    }
}

是滴,我们只需要一个简单的结构类型就可以了!

然后,让我们的 ViewController 遵守 UICollectionViewDataSource 协议,并实现相关方法:

class ViewController: UIViewController, UICollectionViewDataSource {
   
    
    @IBOutlet weak var collectionView: UICollectionView!
    var items = Item.preview
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   
        items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
        cell.layer.cornerRadius = 15.0
        cell.label.text = items[indexPath.row].title
        return cell
    }
    
    override func viewDidLoad() {
   
        super.viewDidLoad()
        
        collectionView.dataSource = self
    }
}

注意,我们并没有让 ViewController 遵守 UICollectionViewDelegate 协议,因为它和这里的拖动操作基本上没有半毛线关系。

4. 遵守拖放代理

上面说过,为了让 UICollectionView 中的 Cell 子视图支持拖放,我们需要先让视图控制器遵守 UICollectionViewDragDelegate 和 UICollectionViewDropDelegate 协议:

extension ViewController: UICollectionViewDragDelegate {
   
    func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
   
        // 保存源 Item 索引
        srcIndex = indexPath
        
        let itemProvider = NSItemProvider(object: "Item" as NSString)
        
        return [UIDragItem(itemProvider: itemProvider)]
    }
}

extension ViewController: UICollectionViewDropDelegate {
   
    func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
   
        // 保存目的 Item 索引
        self.destIndex = destinationIndexPath
        return .init(operation: .move)
    }

	func collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) {
           
        guard let srcIndex, let destIndex else {
    return }
        
        swapItems(from: srcIndex, to: destIndex)
        
        self.srcIndex = nil
        self.destIndex = nil
    }
}

对于上面的代码,需要说明的是:

  • collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) 在拖动开始时被调用,我们可以趁机保存源 Item 的信息;
  • collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) 在拖动中被多次调用,其中传入的 destinationIndexPath 参数表示目的 Cell 的索引(如果下方有的话),我们可以借此保存目的 Item 的信息;
  • collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) 在结束放置时被调用,我们此时可以实现交换对应 Cell 的操作;

随后,我们还需要在 ViewController 中添加所需的属性和方法:

var srcIndex: IndexPath?
var destIndex: IndexPath?

private func swapItems(from srcIndex: IndexPath, to destIndex: IndexPath) {
   
    items.swapAt(srcIndex.row, destIndex.row)
    
    // 将源和目的 Cell 的移动放到批处理中以产生流畅的动画:
    collectionView.performBatchUpdates {
   
        collectionView.moveItem(at: srcIndex, to: destIndex)
        collectionView.moveItem(at: destIndex, to: srcIndex)
    }
}

最后,在视图控制器加载时为其绑定对应的拖放代理,并开启拖动交互:

override func viewDidLoad() {
   
    super.viewDidLoad()
    
    collectionView.dataSource = self
    collectionView.dropDelegate = self
    collectionView.dragDelegate = self
    collectionView.dragInteractionEnabled = true
}

现在,运行 App 看一下效果:

在这里插入图片描述

不过,小伙伴们或许发现了,拖动放置后 Cell 交换会有略微延时,这是怎么回事呢?

5. 更快的响应交换操作

上面 Cell 拖动交换会慢一拍的原因为:我们是在 collectionView(_ collectionView: UICollectionView, dropSessionDidEnd session: UIDropSession) 方法中执行 swapItems() 来完成交换的。

而系统对该方法的回调触发是比较“谨慎”的,它会在判断用户彻底抬起手指后才能得到运行机会。

如果希望用户在目标 Cell 上抬起手指时能够立即完成交换行为,我们可以将 swapItems() 方法放到 UICollectionViewDragDelegate 协议中的 collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) 的回调中去执行,因为该方法识别触发的速度要快得多:

extension ViewController: UICollectionViewDragDelegate {
   
	func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) {
   
	     guard let srcIndex, let destIndex else {
    return }
	    
	    swapItems(from: srcIndex, to: destIndex)
	    
	    self.srcIndex = nil
	    self.destIndex = nil
	}
}

再次运行 App 看一下:

在这里插入图片描述

现在,我们 UICollectionView 中的拖放交换操作的速度又上了一个新台阶,还不快给自己一个大大的赞吗?棒棒哒!💯

总结

在本篇博文中,我们讨论了 UIKit 中 UICollectionView 视图拖放操作的基本原理,并用最简单的代码实现了 UICollectionView 视图中 Cell 的交换功能。

感谢观赏,再会!😎

相关推荐

  1. 】Pytorchregister_buffer()

    2024-02-23 08:46:03       31 阅读
  2. 【WPF.NET开发】WPF

    2024-02-23 08:46:03       37 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-23 08:46:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-23 08:46:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-23 08:46:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-23 08:46:03       20 阅读

热门阅读

  1. haproxy集成国密ssl功能

    2024-02-23 08:46:03       34 阅读
  2. vivado RAM Inference

    2024-02-23 08:46:03       27 阅读
  3. nifi连接Sql server数据库报错TLS问题

    2024-02-23 08:46:03       37 阅读
  4. C++程序设计学习笔记(二)

    2024-02-23 08:46:03       28 阅读
  5. Go 语言一些常用语法编写和优化指南

    2024-02-23 08:46:03       30 阅读
  6. 力扣(leetcode)第455题分发饼干(Python)

    2024-02-23 08:46:03       31 阅读
  7. 嵌入式系统发展前景?

    2024-02-23 08:46:03       28 阅读