How can I change the background image for my NavigationBar on a per page basis?

末鹿安然 提交于 2019-11-30 04:07:32

You need to set some state somewhere about the current page or currently appropriate image to use, probably in each of your viewWillAppear: methods. Then modify your drawRect: function above to reference that state.

To cause the bar to be redrawn, call [myNavigationBar setNeedsDisplay] when you update the state. This will cause drawRect to be invoked.

I'd really recommend reading a tutorial from Sebastian Celis, it really helped me - http://sebastiancelis.com/2009/12/21/adding-background-image-uinavigationbar/

isn't it possible to use an image view (add) on the navigation bar?

I believe this to be the first actual answer to this for iOS5, the main problem being the "removal" of the background image once you are done. Well, just retain the existing image and put it back when you are done.

@implementation MyViewController {
    UIImage *_defaultImage;
}

- (void)viewWillAppear:(BOOL)animated {   
    _defaultImage = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar.png"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController.navigationBar setBackgroundImage:_defaultImage forBarMetrics:UIBarMetricsDefault];
}

You can use this code any where in your application(Call the method in viewWillAppeare:) by calling the method to change the navigation bar image. If You call the method in didFinishLanch means the navigation bar image is set to the whole app.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [[UIDevice currentDevice] systemVersion];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 4.9)
    {
        [self customizeAppearance];
    }

}

- (void)customizeAppearance
{
    UIImage *navbarimage = [[UIImage imageNamed:@"blckapplication_bar.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0,0,0)];
    [[UINavigationBar appearance] setBackgroundImage:navbarimage forBarMetrics:UIBarMetricsDefault];

    // Create resizable images    
    // Set the background image for *all* UINavigationBars
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!