我使用表视图单元格委托方法在 UITableViewCell 中实现了上下文菜单
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration?
func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview?
func tableView(_ tableView: UITableView, previewForDismissingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview?
在我的表格视图单元格内,有一个按钮。通常,长按单元格应该会触发上下文菜单的出现。但是,如果用户长按按钮或按钮的容器,则不会出现上下文菜单,而是触发按钮的操作。
为了解决此问题,我禁用了该按钮并添加了点击手势。此修改允许长按时出现上下文菜单,并且常规点击/单击手势按预期工作。
我有点好奇为什么表视图不能自动处理这种情况以及是否有更优雅的解决方案来解决它。
在 Interface Builder 中关闭按钮和按钮容器上的“用户交互已启用”。然后它应该显示您的上下文菜单。
下面是您必须实现的示例代码:
func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
let provider: UIContextMenuActionProvider = { _ in
UIMenu(title: "Title", children: [
UIAction(title: "Copy") { _ in
// do copy
},
UIAction(title: "Cut") { _ in
// do cut
}
])
}
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: provider)
}