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

Swift中选中UIMenu项弹出UIAlert报错:无present成员的解决方案

解决UIMenu点击后present UIAlertController报错问题

问题原因

报错提示“当前函数不存在present成员”,是因为你代码中的self属于AppDelegate或SceneDelegate这类非UIViewController子类,而只有UIViewController及其子类才有present(_:animated:completion:)方法,无法直接调用该方法弹窗。

解决方案

先实现一个工具方法获取当前活跃的顶层ViewController,再通过这个顶层VC来present弹窗:

  1. 添加获取顶层VC的方法
func getTopViewController() -> UIViewController? {
    guard let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else {
        return nil
    }
    var topVC = keyWindow.rootViewController
    while let presentedVC = topVC?.presentedViewController {
        topVC = presentedVC
    }
    return topVC
}
  1. 修改UIAction的handler代码
let menuActions = UIAction(title: "Create New Profile", image: nil, handler: { [self] (item) in
    // 创建弹窗
    let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to delete this?", preferredStyle: .alert)
    
    // 添加OK按钮
    let okAction = UIAlertAction(title: "OK", style: .default) { _ in
        print("Ok button tapped")
    }
    dialogMessage.addAction(okAction)

    // 通过顶层VC弹窗
    if let topViewController = getTopViewController() {
        topViewController.present(dialogMessage, animated: true)
    }
})

let menu = UIMenu(title: "Profiles", children: [menuActions])
builder.insertSibling(menu, afterMenu: .application)

说明

getTopViewController方法会遍历当前应用的keyWindow,找到最上层的显示ViewController,确保弹窗能正确展示在当前界面之上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:10:21