如何在UIContextMenuInteractionDelegate中识别多视图点击源
先修正代码中的笔误
你的setup()方法里创建了interaction1和interaction2,但添加交互时错误使用了未定义的interaction变量,先修正这部分:
func setup() { let interaction1 = UIContextMenuInteraction(delegate: self) redView.addInteraction(interaction1) let interaction2 = UIContextMenuInteraction(delegate: self) blueView.addInteraction(interaction2) }
区分点击视图的两种方法
方法一:直接判断交互所属的视图
UIContextMenuInteraction的view属性就是它被添加到的视图,直接通过恒等运算符===判断即可:
extension Cell: UIContextMenuInteractionDelegate { func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { suggestedActions in var menu: UIMenu if interaction.view === self.redView { // 构建redView对应的菜单 let action1 = UIAction(title: "红色视图操作1", image: UIImage(systemName: "circle.fill")) { _ in // 执行对应操作 } menu = UIMenu(title: "", children: [action1]) } else if interaction.view === self.blueView { // 构建blueView对应的菜单 let action2 = UIAction(title: "蓝色视图操作2", image: UIImage(systemName: "square.fill")) { _ in // 执行对应操作 } menu = UIMenu(title: "", children: [action2]) } else { // 其他情况,返回默认菜单或nil return nil } return menu }) } }
方法二:给视图设置Tag标记
如果后续视图数量较多,也可以给视图设置tag来区分:
- 在初始化视图时设置tag:
let redView = UIView() redView.tag = 1001 let blueView = UIView() blueView.tag = 1002
- 在代理方法中通过
interaction.view?.tag判断:
extension Cell: UIContextMenuInteractionDelegate { func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { suggestedActions in guard let tag = interaction.view?.tag else { return nil } var menu: UIMenu switch tag { case 1001: // 红色视图专属菜单 let action1 = UIAction(title: "红色视图操作1") { _ in } menu = UIMenu(children: [action1]) case 1002: // 蓝色视图专属菜单 let action2 = UIAction(title: "蓝色视图操作2") { _ in } menu = UIMenu(children: [action2]) default: return nil } return menu }) } }
两种方法中,方法一更直观且不易出错,推荐优先使用。
内容的提问来源于stack exchange,提问作者Murat Merekov
相关产品推荐
相关产品推荐

