Best point to overwrite the navigationBar property

2019-09-05 02:52发布

问题:

I'm overwriting UINavigationController to replace the default navigationBar property with an instance of my own subclass of UINavigationBar. So I tried something like

_navigationBar = [[SBNavigationBar alloc] init];

in my -initWithRootViewController:. But that didn't work out as I expected it. There's still the default navigationBar being displayed.

So what's the best point to overwrite the navigationBar?

Thanks in advance
–f

回答1:

If you check the documentation http://developer.apple.com/iphone/library/documentation/uikit/reference/UINavigationController_Class/Reference/Reference.html, you'll see that the navigationBar property is read-only.

To have a custom navigationBar you can use Categories for example. You will find many questions answering this here on stackoverflow.

One simple version is putting an image in drawRect: like so...

@implementation UINavigationBar (Custom)

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

@end