IOS工具相关

iOS-导航栏变透明的几种方法

2017-08-26  本文已影响987人  Simple_Code

方法一:

在当前页面加入下面方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //去掉导航栏底部的黑线
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}
如果仅设置当前页导航透明,需加入下面方法
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

需要注意的是:如果返回上一页的操作有动画,则在上一页出现的时候,导航栏的颜色会逐渐变化

方法二:类似于方法一

    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;
}

方法三:

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;
}
仅设置当前页面
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 1;
}

方法四:

- (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;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读