WKWebView操作表关闭后连带关闭呈现视图控制器问题求助
这种情况我之前也碰到过,大概率是代码里的某个细节处理不当导致的,咱们一步步排查定位:
1. 先检查操作表的回调逻辑
首先确认你创建操作表(不管是用UIAlertController还是旧的UIActionSheet)的代码里,有没有在按钮的handler中误调用了导航栈弹出方法,比如self.navigationController?.popViewController(animated: true)或者popToRootViewController。
给你贴一个正确的UIAlertController操作表示例:
func showContentActionSheet(for content: String) { let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // 复制按钮逻辑 let copyAction = UIAlertAction(title: "复制", style: .default) { _ in UIPasteboard.general.string = content // 这里只处理复制,绝对不要加pop相关代码 } actionSheet.addAction(copyAction) // 分享按钮逻辑 let shareAction = UIAlertAction(title: "分享", style: .default) { _ in let shareVC = UIActivityViewController(activityItems: [content], applicationActivities: nil) self.present(shareVC, animated: true) // 同样,只处理分享逻辑,别碰导航栈 } actionSheet.addAction(shareAction) // 取消按钮 let cancelAction = UIAlertAction(title: "取消", style: .cancel) actionSheet.addAction(cancelAction) present(actionSheet, animated: true) }
2. 排查导航栏返回按钮的自定义逻辑
如果你自定义了导航栏的返回按钮,一定要检查其target-action绑定是否正确。比如是不是不小心把返回按钮的点击事件绑定到了popToRootViewController,而不是popViewController:
❌ 错误示例:
let backButton = UIBarButtonItem(title: "< 返回", style: .plain, target: self, action: #selector(popToRoot))
✅ 正确示例:
@objc func popCurrentVC() { navigationController?.popViewController(animated: true) } // 绑定返回按钮时 let backButton = UIBarButtonItem(title: "< 返回", style: .plain, target: self, action: #selector(popCurrentVC)) navigationItem.leftBarButtonItem = backButton
3. 检查导航控制器代理与手势冲突
如果你的导航控制器设置了代理,检查navigationController(_:didShow:animated:)等代理方法中,有没有意外修改导航栈的逻辑。另外,WKWebView的长按手势可能和导航控制器的交互式侧滑返回手势冲突,导致操作表关闭时误触发侧滑pop。可以尝试在弹出操作表时临时禁用侧滑手势,关闭后恢复:
// 弹出操作表前禁用侧滑手势 navigationController?.interactivePopGestureRecognizer?.isEnabled = false present(actionSheet, animated: true) { // 操作表关闭后恢复手势 self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true }
4. 排查WKWebView的代理逻辑
检查WKWebView的代理方法,比如webView(_:decidePolicyFor:decisionHandler:),有没有在某些条件下错误地调用了导航栈弹出方法。比如判断URL时误触发pop,也会导致操作表关闭时VC被弹出。
5. 检查视图控制器的生命周期方法
最后,查看WKWebViewController的viewWillDisappear、viewDidDisappear等生命周期方法,有没有在其中加入了pop相关的逻辑——比如误判了视图消失的原因,不管什么情况都执行pop。
如果以上步骤都排查完还是没解决,可以把你创建操作表的代码和导航控制器相关的代码贴出来,我再帮你细化分析~
内容的提问来源于stack exchange,提问作者ferasfa

