前言:
在開發(fā)中,為了美觀很多設(shè)計成導(dǎo)航欄透明的樣式,下面就列舉一下實現(xiàn)導(dǎo)航欄透明的幾種方法
第一種方法:
- (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 底部的細(xì)線
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;
}
注意點:
設(shè)置導(dǎo)航欄透明的時候,如果在Push到其他的控制器,其他的控制器導(dǎo)航欄也是會變得透明,所以為了防止這類情況的發(fā)生,最好在- (void)viewWillDisappear:(BOOL)animated
方法中,把導(dǎo)航欄的顏色還原過來