提示: 本篇以Swift代碼講解, 最下面為OC代碼, 如果有問題請留言
問題描述
-
當在iPhoneX模擬器上運行程序時, 如果在push的時候設置了控制器的hidesBottomBarWhenPushed屬性為true, 那么push過程中有如下效果:
tabBar上移問題 - 圖中可以發現, push過程中隱藏tabBar會導致tabBar上移一段距離
解決思路
- 問題出現是在push過程中, 所以我們只需要攔截push過程即可, 即重寫push方法, 并調整tabBar的位置
- 第一步: 自定義導航控制器, 重寫push方法(項目中大家基本都會這么做)
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
super.pushViewController(viewController, animated: animated)
}
- 第二步: 設置push控制器的hidesBottomBarWhenPushed為true
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if childViewControllers.count > 0 {
// push時隱藏tabBar
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
}
- 第三步: 在spuer之后修改tabBar的frame
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if childViewControllers.count > 0 {
// push時隱藏tabBar
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
// 獲取tabBar的frame, 如果沒有直接返回
guard var frame = self.tabBarController?.tabBar.frame else {
return
}
// 設置frame的y值, y = 屏幕高度 - tabBar高度
frame.origin.y = UIScreen.main.bounds.size.height - frame.size.height
// 修改tabBar的frame
self.tabBarController?.tabBar.frame = frame
}
最后效果
-
push過程中, 隱藏tabBar, 并且tabBar位置不變
push過程中, 隱藏tabBar, 并且tabBar位置不變
OC版本代碼如下:
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
if (self.childViewControllers.count > 0) {
// push過程中隱藏tabBar
viewController.hidesBottomBarWhenPushed = YES;
}
// 重寫super
[super pushViewController:viewController animated:animated];
// 修改tabBra的frame
CGRect frame = self.tabBarController.tabBar.frame;
frame.origin.y = [UIScreen mainScreen].bounds.size.height - frame.size.height;
self.tabBarController.tabBar.frame = frame;
}