Swift中选中UIMenu项弹出UIAlert报错:无present成员的解决方案
问题原因
报错提示“当前函数不存在present成员”,是因为你代码中的self属于AppDelegate或SceneDelegate这类非UIViewController子类,而只有UIViewController及其子类才有present(_:animated:completion:)方法,无法直接调用该方法弹窗。
解决方案
先实现一个工具方法获取当前活跃的顶层ViewController,再通过这个顶层VC来present弹窗:
- 添加获取顶层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 }
- 修改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
相关产品推荐
相关产品推荐

