前言:
在开发中,为了美观很多设计成导航栏透明的样式,下面就列举一下实现导航栏透明的几种方法
第一种方法:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
for (UIView *aView in self.navigationController.navigationBar.subviews) {
if ([aView isKindOfClass:NSClassFromString(@"_UINavigationBarBackground")]) {
aView.hidden = YES;
}
}
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
for (UIView *aView in self.navigationController.navigationBar.subviews) {
if ([aView isKindOfClass:NSClassFromString(@"_UINavigationBarBackground")]) {
aView.hidden = NO;
}
}
}
第二种方法:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去除 navigationBar 底部的细线
self.navigationController.navigationBar.shadowImage = [UIImage new];
第三种方法
self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
UIImage *image = [self createAImageWithColor:[UIColor clearColor] alpha:0.0];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
- (UIImage *)createAImageWithColor:(UIColor *)color alpha:(CGFloat)alpha{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextSetAlpha(context, alpha);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
注意点:
设置导航栏透明的时候,如果在Push到其他的控制器,其他的控制器导航栏也是会变得透明,所以为了防止这类情况的发生,最好在- (void)viewWillDisappear:(BOOL)animated
方法中,把导航栏的颜色还原过来