如何观察UITabBar是否隐藏的事件



我在推送时用hidesBottomBarWhenPushed的方法,在很多地方,UITabBar 在推送时需要隐藏,在弹出时需要不隐藏,那么如何观察事件呢?

实际上还有另一种观察方式,如果 UITabBar 是否隐藏,那就是使用键值观察 (KVO(。我遇到了类似的问题,并用它来查找tabBar何时显示或隐藏。

它可能看起来像这样。

class TabBarController: UITabBarController {
  // custom code
  var observation: NSKeyValueObservation?
  convenience init() {
      self.init(nibName: nil, bundle: nil)
      
      observation = observe(
          .tabBar.isHidden,
          options: [.old, .new]
      ) { object, change in
          print("TabBar isHidden changed from : (change.oldValue), updated to: (change.newValue)")
      }
  }
  deinit { 
      observation = nil
  }
}

如果在生产中使用它,请确保删除观察器并遵循 KVO 的最佳实践。希望对您有所帮助。

没有委托或通知供您了解选项卡栏是否可见。您可以检查选项卡栏的窗口属性

if tabBarController!.tabBar.window == nil {
}

或隐藏底部栏何时推送

if hidesBottomBarWhenPushed {
}

来变通。

最新更新