无UINavigationController时,点击Alert按钮跳转UIViewController的实现方法
嘿,这个问题我熟!既然你的UITableViewController没有嵌入UINavigationController,那咱们直接用present(_:animated:completion:)方法就能完成跳转,结合你的自定义AlertController,只需要做两处小修改:
第一步:给自定义AlertController添加回调闭包
首先要让你的自定义AlertController能通知主页面“用户点击了前往购物车按钮”,所以我们给它加个回调闭包:
class AlertController: UIAlertController { // 新增:跳转购物车的回调闭包 var onGoToCart: (() -> Void)? static func instance(title: String) -> AlertController { let alert = AlertController(title: title, message: nil, preferredStyle: .alert) // 「前往购物车页面」按钮 let goToCartAction = UIAlertAction(title: "前往购物车页面", style: .default) { [weak self] _ in // 触发回调 self?.onGoToCart?() } alert.addAction(goToCartAction) // 「停留在当前页面」取消按钮 let stayAction = UIAlertAction(title: "停留在当前页面", style: .cancel) alert.addAction(stayAction) // 保留你原本的自定义动画代码 return alert } // 你的自定义动画实现代码... }
第二步:在UITableViewController中绑定跳转逻辑
接下来回到你的UITableViewController代码里,在present Alert的时候,给回调闭包赋值,实现跳转:
if user?.uid != nil { let title = "Item is added to your cart " let alert = AlertController.instance(title: title) // 绑定跳转逻辑 alert.onGoToCart = { [weak self] in // 实例化你的购物车页面,这里假设类名为CartTableViewController let cartVC = CartTableViewController() // 可选:如果购物车页面需要导航栏(比如返回按钮),可以用UINavigationController包裹 // let navCartVC = UINavigationController(rootViewController: cartVC) // self?.present(navCartVC, animated: true, completion: nil) // 直接present购物车页面 self?.present(cartVC, animated: true, completion: nil) } present(alert, animated: true, completion: nil) } else { // 提示用户注册.. }
一些小提示
- 记得把
CartTableViewController替换成你实际的购物车页面类名哦。 - 使用
[weak self]是为了避免循环引用,防止内存泄漏,这个细节别忘啦。 - 如果希望购物车页面有返回按钮,就用UINavigationController包裹后再present,用户点击返回就能回到当前页面。
内容的提问来源于stack exchange,提问作者Amal Nasir
相关产品推荐
相关产品推荐

