iOS - 实现导航栏透明的几种方法(总结)

前言:

在开发中,为了美观很多设计成导航栏透明的样式,下面就列举一下实现导航栏透明的几种方法

第一种方法:
- (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方法中,把导航栏的颜色还原过来

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容