如何在点击按钮后立即激活拖动和排序模式

How to you activate drag and order mode immediately after you tap on a button

基于https://github.com/pgpt10/DragAndDrop-CollectionView

通过使用

self.collectionView.dragInteractionEnabled = true
self.collectionView.dragDelegate = self
self.collectionView.dropDelegate = self

一旦您长按 collection 视图单元格中的任意位置,将触发以下功能

extension DragDropViewController : UICollectionViewDragDelegate
{
    func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem]
    {
        let item = collectionView == collectionView1 ? self.items1[indexPath.row] : self.items2[indexPath.row]
        let itemProvider = NSItemProvider(object: item as NSString)
        let dragItem = UIDragItem(itemProvider: itemProvider)
        dragItem.localObject = item
        return [dragItem]
    }
    

但是,我有不同的要求。

我有一个 collection 如下所示

我希望当用户点击(而不是长按)右边的3条横线图标时,他可以立即执行拖动和重新排序。点击其他区域,或长按单元格,不会有拖动和重新排序的效果。

我可以知道如何实现吗?


App Store 中一些著名的应用程序能够实现此功能

我注意到Google保留在App Store,能够实现这样的功能。只需点击他们的待办事项列表中最左边的图标,我们就可以立即重新排序待办事项列表项。

想知道他们是怎么做到的吗?


方法 1:在 Cell 的重新排序图标上安装长按手势

我试过了

  1. 在单元格的重新排序图标上安装长 UILongPressGestureRecognizer

  2. 使用 gesture.minimumPressDuration = 0 模仿点击行为。

    class TabInfoSettingsItemCell:UICollectionViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
    
        ...
    
        let gesture = UILongPressGestureRecognizer(target:self, action: #selector(longPressGesture))
        gesture.minimumPressDuration = 0
        reorderImageView.addGestureRecognizer(gesture)
    }
    

但结果并不令人鼓舞。 “移动”操作根本不起作用!

完整的代码可以在这里找到:https://github.com/yccheok/ios-tutorial/tree/gesture-on-cell/TabDemo


方法 2:在 Collection 视图

上安装长按手势

我试过了

  1. 在 Collection 视图上安装 long UILongPressGestureRecognizer
  2. 使用 gesture.minimumPressDuration = 0 模仿点击行为。

这是代码片段

let gesture = UILongPressGestureRecognizer(target:self, action: #selector(longPressGesture))
 // Mimic short tap. But this blocks the events for delete button and text field :-(
 gesture.minimumPressDuration = 0
 collectionView.addGestureRecognizer(gesture)

但结果并不完美。

  1. 我们如何才能识别仅在重新排序图标(具有 3 条水平线的图标)边界内的点击事件。
  2. 删除按钮不再有效,因为 UILongPressGestureRecognizer 阻止它接收事件。
  3. 文本字段不再工作,因为 UILongPressGestureRecognizer 阻止它接收事件。

完整的代码可以在这里找到:https://github.com/yccheok/ios-tutorial/tree/gesture-on-collection-view/TabDemo

UICollectionView 中删除 UILongPressGestureRecognizer,从 TabInfoSettingsItemCell 中删除手势注释 class . 在 TabInfoSettingsController:

中替换此方法
func changed(_ gesture: UILongPressGestureRecognizer) {
    print("==changed==")
    collectionView?.updateInteractiveMovementTargetPosition(gesture.location(in: collectionView))
}

然后尝试一下。