免费开源的iOS开发学习平台

UINavigationController介绍:7-导航栏设置背景图片

默认情况下,导航栏使用的是近似于白色的纯色背景,然而在实际的开发过程中,为了展示更加丰富的效果,我们也可以为导航栏添加一个整体的背景图片。在UINavigationBar类中,提供了setBackgroundImag:forBarMetrics:方法,该方法可以为导航栏添加背景图片。

- (void)setBackgroundImage:(nullable UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics;

下方的示例代码实现了为导航栏添加一个背景图片功能。

  • 预先导入background_normal图片,如果图片需要拉伸显示的话,可以使用Slicing功能进行设置

  • 在AppDelegate.m文件中,添加如下代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
    UIViewController *navRootVC = [[UIViewController alloc] init];
    navRootVC.view.backgroundColor = [UIColor whiteColor];
        
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:navRootVC];
    navVC.navigationBar.barStyle = UIBarStyleDefault;
    
    [navVC.navigationBar setBackgroundImage:[UIImage imageNamed:@"background_normal"] forBarMetrics:UIBarMetricsDefault];
    
    navRootVC.title = @"99iOS.com";
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = navVC;
    [self.window makeKeyAndVisible];
    
    return YES;
}

运行后,导航栏样式如下。

示例代码

https://github.com/99ios/9.2.7