You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将上下文菜单限定在单个UICollectionView中

问题解决:UICollectionView上下文菜单仅指定视图显示的错误修复

你遇到的报错原因很明确:取消注释判断语句后,只有当CollectionView是list_CollectionView_Outlet时,代码才会返回configuration;但当触发方法的是另外两个CollectionView时,函数没有返回任何值,而Swift要求这个代理方法必须返回UIContextMenuConfiguration?类型的结果,因此编译器报错。

修复后的代码

extension Case_VC2: UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration?
    {
        // 仅为指定的CollectionView生成上下文菜单
        guard collectionView == list_CollectionView_Outlet else {
            // 其他CollectionView返回nil,不显示菜单
            return nil
        }
        
        gID = theCurrentArray[indexPath.row].ID
        name = theCurrentArray[indexPath.row].Name
        
        let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in
            
            let edit = UIAction(title: K.Titles.edit, image: UIImage(named: "Edit2")) { _ in
                gHideBackBtn = false
                gTheDisabledCell = ""
                self?.addEditTrick()
            }
            
            let remove = UIAction(title: K.Titles.remove, image: UIImage(systemName: K.Icons.trash)) { _ in
                self?.delete_XRef_Item()
            }
            
            return UIMenu(title: "", image: nil, children: [edit, remove])
        }
        
        return configuration
    }
}

核心逻辑说明

用guard语句做前置判断:

  • 如果当前触发方法的是目标CollectionView,就继续执行生成上下文菜单的代码并返回配置;
  • 如果是其他CollectionView,直接返回nil,这样就覆盖了所有代码路径的返回要求,编译器不会再报错。

你也可以用普通的if-else结构实现同样效果:

if collectionView == list_CollectionView_Outlet {
    // 生成并返回configuration的代码
} else {
    return nil
}

内容的提问来源于stack exchange,提问作者user11004336

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:56:02