注:本文所有图片保存EverNote 印象笔记(www.yinxiang.com)当中, 如果有其帐号登录后即可查看全部图片。 如没有帐号可用e-mail 注册免费印象笔记
iOS下完美隐藏tabBar和navigationBar 的方案。
tags: IOS
教程
应用描述
我做一个小应用需要有如下功能,当点击一个tabBar的子窗口时,需要隐藏导航条和tab工具栏。再次点击时,又重新显示。
以下正常情况(为演示清楚,我画上两条红带):
不成功的办法
第一种办法:参考一个项目源码,将tabBar的alpha设为0,这样的确可以隐藏工具栏,但是会在工具栏的区域显示一个黑条。代码如下
+ (void)hideTabBar:(UIView*)tabBar hide:(BOOL)hide animated:(BOOL)animated
{
//UIView*tabBar = self.tabBarController.tabBar;
if (animated)
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:nil];
[UIView setAnimationDuration:0.5];
}
[tabBar setAlpha:hide ? 0.0 : 1.0];
if (animated)
{
[UIView commitAnimations];
}
}
显示效果如下:
另一种方法是 设置这个对象的hidden 属性,设为YES就是隐藏 如
self.tabBarController.tabBar.hidden = YES;
但是效果同上,仍然不成功。
成功方法
测试成功,点击后效果
这个代码的思路,当隐藏时,是把中间显示的content View,扩展到全屏,当显示时间又收缩成原样。
我现在把这两个方法写成一个静态工具方法,大家只要把当前UIViewController的指针传入即可。
+ (void)hideTabBar:(UIViewController*)viewController{ if( (viewController.tabBarController == NULL) || (viewController.tabBarController.tabBar == NULL)) return ; UINavigationBar * navbar = NULL; UITabBar *tabBar = viewController.tabBarController.tabBar; if( (viewController.navigationController.navigationBar != NULL) || (viewController.navigationController.navigationBar != NULL) ) navbar = viewController.navigationController.navigationBar; //内容显示区 UIView *contentView; if ( [[viewController.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] ) contentView = [viewController.tabBarController.view.subviews objectAtIndex:1]; else contentView = [viewController.tabBarController.view.subviews objectAtIndex:0]; if(tabBar.hidden == NO) { [ contentView setFrame:CGRectMake(contentView.bounds.origin.x,contentView.bounds.origin.y, contentView.bounds.size.width, contentView.bounds.size.height + tabBar.frame.size.height)]; [ tabBar setHidden:YES ]; [ navbar setHidden:YES ]; } else { [contentView setFrame:CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y, contentView.bounds.size.width, contentView.bounds.size.height - tabBar.frame.size.height)]; [ tabBar setHidden:NO ]; [ navbar setHidden:NO ]; } }
如图片不正常请访问 完整版
https://app.yinxiang.com/shard/s1/sh/4d2992b8-97e1-44c2-bd5d-75ba0115ef50/65253dc9a9339b91c2712c3bb63bbafd