How to change the background image for my navigation block based on each page?

I was looking for a way to change my background image NavigationBarand control my appearance NavigationBarwhen a user navigates to the application.

I understand that the accepted approach for changing the background image is:

@implementation UINavigationBar (UINavigationBarCategory)

- (void)drawRect:(CGRect)rect {
     UIImage *image = [UIImage imageNamed: @"navbar.png"];
     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

However, this changes the look of NavigationBarthe entire application. How to change the background image NavBarwhen the user switches from one view to another?

Thanks in advance for your help!

+3
source share
5 answers

- - , , viewWillAppear:. drawRect: , .

, [myNavigationBar setNeedsDisplay] . drawRect.

+2

() ?

0

, iOS5, "" , . , , .

@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];
}
0

( viewWillAppeare:), . didFinishLanch, .

- (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
}
0

Source: https://habr.com/ru/post/1759671/


All Articles