创建一个不UINavigationBar
包含任何方法的子类,除了drawRect:
. 如果需要,将自定义绘图代码放在那里,否则将其留空(但实现它)。
接下来,将UINavigationController
的导航栏设置为此子类。在代码中使用initWithNavigationBarClass:toolBarClass:
,或者如果您正在使用故事板/笔尖,则只需在 Interface Builder 中更改它(它是侧面层次结构中 UINavigationController 的子类)。
最后,获取导航栏的引用,以便我们可以在包含的视图控制器中配置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];
}
这是模仿瘟疫的结果的屏幕截图。

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