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