如何从TabBarController获取上一个Tab索引?解决Alert背景显示问题
如何在TabBarController中记录并获取上一个选中的Tab索引
首先得明确:系统原生的UITabBarController并没有内置保存上一个选中索引的属性,所以我们得自己动手实现这个逻辑,步骤其实很简单:
1. 自定义你的TabBarController
先创建一个继承自UITabBarController的子类,比如叫CustomTabBarController,然后添加一个属性来存储上一次选中的索引:
class CustomTabBarController: UITabBarController { // 初始化时默认设为0,和初始选中索引保持一致 private var previousSelectedIndex = 0 override func viewDidLoad() { super.viewDidLoad() // 设置代理,监听Tab切换事件 self.delegate = self } }
2. 实现TabBarControllerDelegate方法,记录上一个索引
通过代理方法tabBarController(_:shouldSelect:)来捕获切换前的索引(这个方法在Tab切换前触发,能准确记录上一个选中项):
extension CustomTabBarController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { // 先把当前选中的索引存为上一个索引 if let currentIndex = tabBarController.viewControllers?.firstIndex(of: tabBarController.selectedViewController ?? UIViewController()) { previousSelectedIndex = currentIndex } return true // 返回true允许Tab切换 } // 如果需要在切换完成后做操作,也可以用didSelect方法,此时previousSelectedIndex已经是切换前的索引了 func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { print("上一个选中的Tab索引:\(previousSelectedIndex)") } }
3. 用上一个索引处理Alert背景逻辑
现在当你需要打开Alert时,就可以通过自定义TabBarController的实例拿到这个上一个索引,进而获取对应的视图控制器来处理背景:
// 假设你在某个子ViewController中需要获取上一个索引 if let tabBarController = self.tabBarController as? CustomTabBarController { let lastSelectedIndex = tabBarController.previousSelectedIndex // 这里就可以用lastSelectedIndex对应的VC来实现"以上一个页面为Alert背景"的逻辑了 // 比如可以临时切换回上一个VC展示Alert,之后再切回当前Tab;或者调整Alert的present层级 }
额外提示
- 如果是用Objective-C开发,逻辑完全一致:自定义
UITabBarController子类,添加NSInteger类型的属性记录上一个索引,然后实现UITabBarControllerDelegate的tabBarController:shouldSelectViewController:方法更新属性即可。 - 首次打开App时,因为还没切换过Tab,
previousSelectedIndex会保持初始值0,和当前选中索引一致,这是合理的默认状态。
内容的提问来源于stack exchange,提问作者Shangari C
相关产品推荐
相关产品推荐

