带透明导航栏的可见按钮

时间:2012-11-17 15:28:13

标签: objective-c ios

我见过几个具有完全透明导航栏但带有可见按钮的应用程序,我似乎无法找到任何不会使按钮隐形的东西。我确定他们正在使用UINavigationController作为导航栏,因为它具有与淡入淡出相同的动画,而不是。

我目前在ViewDidLoad和ViewDidAppear中使用此代码来隐藏或显示导航栏,因为它不应该在第一页上 -

[self.navigationController setNavigationBarHidden:NO animated:YES];

这段代码的透明度:

[self.navigationController.navigationBar setAlpha:0.0];

3 个答案:

答案 0 :(得分:7)

创建UINavigationBar的子类,不包含除drawRect:之外的任何方法。如果需要,可以在那里放置自定义绘图代码,否则将其留空(但实现它)。

接下来,将UINavigationController的导航栏设置为此子类。在代码中使用initWithNavigationBarClass:toolBarClass:,或者如果您正在使用storyboards / nib(它是侧面层次结构中UINavigationController的子类),只需在Interface Builder中更改它。

最后,获取对导航栏的引用,以便我们可以使用所包含视图控制器的self.navigationController.navigationBar中的loadView对其进行配置。将导航栏的translucent设置为YES,将backgroundColor设置为[UIColor clearColor]。示例如下。

//CustomNavigationBar.h
#import <UIKit/UIKit.h>

@interface CustomNavigationBar : UINavigationBar
@end

//CustomNavigationBar.m
#import "CustomNavigationBar.h"

@implementation CustomNavigationBar

- (void)drawRect:(CGRect)rect {}

@end

//Put this in the implementation of the view controller displayed by the navigation controller
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = YES;
    [self navigationController].navigationBar.backgroundColor = [UIColor clearColor];
}

这是结果的屏幕截图,模仿瘟疫。

enter image description here

drawRect:中绘制了蓝色边框,以向您显示UINavigationBar,而不仅仅是按钮和标签。我在子类中实现了sizeThatFits:以使条形更高。按钮和标签都是UIView,其中包含作为UIBarButtonItems放置在栏中的正确UI元素。我首先将它们嵌入到视图中,以便我可以更改它们的垂直对齐方式(否则,当我实现sizeThatFits:时,它们会“卡在”底部。)

答案 1 :(得分:1)

要使导航栏透明,请使用以下代码:

self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
self.navigationController.navigationBar.tintColor = [UIColor clearColor];
self.navigationController.navigationBar.translucent = YES;

在此之后使用以下属性设置导航栏的背景图像与其后面的视图相同:

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"SAMPLE.jpg"] forBarMetrics:UIBarMetricsDefault];

答案 2 :(得分:1)

self.navigationController.navigationBar.translucent = YES; // Setting this slides the view up, underneath the nav bar (otherwise it'll appear black)
const float colorMask[6] = {222, 255, 222, 255, 222, 255};
UIImage *img = [[UIImage alloc] init];
UIImage *maskedImage = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(img.CGImage, colorMask)];

[self.navigationController.navigationBar setBackgroundImage:maskedImage forBarMetrics:UIBarMetricsDefault];
//remove shadow
    [[UINavigationBar appearance] setShadowImage: [[UIImage alloc] init]];