NavigationBar相关的问题

来源:互联网 发布:25颗摇头矩阵灯厂家 编辑:程序博客网 时间:2024/06/05 06:39

基本用法

1 设置NavigationBar标题大小及颜色

NSDictionary  *textAttributes=@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont systemFontOfSize:20]};[self.navigationController.navigationBar setTitleTextAttributes:textAttributes];

2 NavigationBar设置中间的标题或者自定义View

[self.navigationItem setTitle:@"标题"];[self.navigationItem setTitleView:imageView];

自定义导航栏颜色

有几种方案可以设置导航栏的

设置背景颜色

首先因为UINavigationBar是UIView的子类,但是却不能直接设置UINavigationBar的背景颜色,显示还是有问题的

self.navigationController.navigationBar.backgroundColor = [UIColor redColor];

看了一下UINavigationBar的属性,其中有barTintColor的属性,可以设置背景颜色,需要注意的是* iOS7之后 tintColor 已经没有作用了,需要使用 barTintColor 设置背景颜色

[self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];

如果设置了顶部为半透明的效果,设置translucent为NO便可以解决

如果有黑色的分割线,可以通过设置背景图片的方式去除

[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

两个属性需要成对的设置

设置背景图片

除了使用背景颜色外,还可以使用背景图片

[navigationBar setBackgroundImage:[UIImage imageNamed:@"image"]                   forBarPosition:UIBarPositionAny                       barMetrics:UIBarMetricsDefault];[navigationBar setShadowImage:[[UIImage alloc] init]];

如果使用了背景颜色,背景图片还是可以盖住背景颜色的

比如可以设置一张透明的背景图片,设置alpha=0
NavigationBar 的背景是透明的,但是导航栏的按钮仍可以显示
然后设置 edgesForExtendedLayout 为 UIRectEdgeAll,并且设置 automaticallyAdjustsScrollViewInsets 为 NO,这样也可以实现需要的效果
当然,苹果官方并不建议对导航栏进行setHidden和setTranslucent以外的操作

隐藏NavigationBar

另外还可以隐藏NavigationBar

[self.navigationController setNavigationBarHidden:YES animated:animated]

隐藏了系统导航栏后,会遇到了一个问题

复现的步骤:
1 在隐藏导航栏的页面进入下一个页面
2 在下一个页面滑动返回到一半终止返回
3 再次滑动返回,就会发现导航栏错位

参考demo:https://github.com/aksh1t/iOSNavigationBug 可以复现这个bug

原因是在 viewWillAppear: 设置了导航栏的状态
http://stackoverflow.com/questions/23261304/navigation-bar-title-bug-with-interactivepopgesturerecognizer 中详细的讲了该问题产生的原因
因为在右滑的过程中,执行了之前的ViewController中的viewWillAppear方法,其中设置了导航栏的状态,从而导致导航栏错乱

修复方法(答案中提到的几个方案)
1 设置 animated 为 YES
2 把设置导航栏的操作写到 viewDidAppear 中 (影响显示效果)
3 直接设置 navigationController.navigationBar.hidden 而不是使用 navigationController setNavigationBarHidden
4 最后的方法可以参考 stackoverflow 中的方法

-(void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated];    id<UIViewControllerTransitionCoordinator> tc = self.transitionCoordinator;    if (tc && [tc initiallyInteractive]) {        [tc notifyWhenInteractionEndsUsingBlock:         ^(id<UIViewControllerTransitionCoordinatorContext> context) {             if ([context isCancelled]) {                 // do nothing!             } else { // not cancelled, do it                 [self.navigationController setNavigationBarHidden:YES animated:NO];             }         }];    } else { // not interactive, do it        [self.navigationController setNavigationBarHidden:YES animated:NO];    }}

即如果右滑取消的话,则不执行 viewWillAppear: 中的方法

0 0