Custom uinavigatonbar exception

2019-07-11 05:59发布

问题:

I've made a custom uinavigation bar this way:

@implementation UINavigationBar (UINavigationBarCategory)

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

@end

Now I'd like to add exception to show the normal uinavigation bar when i load an specific viewcontroller into de navigationcontroller.

How can I code that exception?

回答1:

I don't think that's possible with a category on UINavigationBar. I would suggest a subclass, say CustomNavigationBar

.h

#import <UIKit/UIKit.h>

@interface CustomNavigationBar : UINavigationBar {
}
@end

.m

#import "CustomNavigationBar.h"

@implementation CustomNavigationBar

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

@end

The tricky thing is that you never create a UINavigationBar yourself, it's all handled by UIKit. To change the appearance of some bars only, you'll have to manually change their class at runtime.

Import

#import <objc/runtime.h>

And in your view controller (in viewDidLoad for example), add

object_setClass(self.navigationController.navigationBar, [CustomNavigationBar class]);