如何知道 (iOS 13+) configurationForMenuAtLocation 上的上下文菜单触发了哪个 UICollectionView 单元格

How to know which UICollectionView cell is triggered for context menu on (iOS 13+) configurationForMenuAtLocation

在 iOS 13,我们有漂亮的 tableView 和 collectionView 上下文菜单。

我在 UICollectionView 上使用它是这样的:

'cellForItemAt indexPath' 上的实施:

let interaction = UIContextMenuInteraction(delegate: self)
cell.moreButton.isUserInteractionEnabled = false
cell.moreButton.tag = indexPath.row
cell.addInteraction(interaction)

在 'configurationForMenuAtLocation location'

处理老虎
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
        let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
            var actions = [UIAction]()
            for item in self.contextMenuItems {
                let action = UIAction(title: item.title, image: item.image, identifier: nil, discoverabilityTitle: nil) { _ in
                self.didSelectContextMenu(index: 0) <== how pass the index from here? 
          }
         actions.append(action)
       }
      let cancel = UIAction(title: "Cancel", attributes: .destructive) { _ in}
      actions.append(cancel)
      return UIMenu(title: "", children: actions)
    }
  return configuration
}

问题是我怎么知道collectionView的哪个索引触发了这个菜单?

好的,我找到了解决方案!

我应该使用 'contextMenuConfigurationForItemAt' 而不是 'configurationForMenuAtLocation'。

像这样:

@available(iOS 13.0, *)
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
    return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { suggestedActions in
        return self.makeContextMenu(for: indexPath.row)
    })
}

然后使用这个:

@available(iOS 13.0, *)
func makeContextMenu(for index:Int) -> UIMenu {
    var actions = [UIAction]()
    for item in self.contextMenuItems {
        let action = UIAction(title: item.title, image: item.image, identifier: nil, discoverabilityTitle: nil) { _ in
            self.didSelectContextMenu(menuIndex: item.index, cellIndex: index)  // Here I have both cell index & context menu item index
        }
        actions.append(action)
    }
    let cancel = UIAction(title: "Cancel", attributes: .destructive) { _ in}
    actions.append(cancel)
    return UIMenu(title: "", children: actions)
}

这是我的上下文菜单项:

let contextMenuItems = [
    ContextMenuItem(title: "Edit", image: IMAGE, index: 0),
    ContextMenuItem(title: "Remove", image: IMAGE, index: 1),
    ContextMenuItem(title: "Promote", image: IMAGE, index: 2)
]

这是我的 ContextMenuItem:

struct ContextMenuItem {
  var title = ""
  var image = UIImage()
  var index = 0
}