Why doesn’t this work? I want to sublcass UINavigationBar so in xcode I click new file -> objective c class,
class: CustomNavBar
subclass of: UINavigationBar
then in the storyboard under the navigation controller scene, I click on the Navigation Bar and set it’s class to CustomNavBar.
I then go into my CustomNaVBar class and have tried to add a custom image background.
In the initWithFram method I have added this:
- (id)initWithFrame:(CGRect)frame
{
NSLog(@"Does it get here?"); //no
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIImage *image = [UIImage imageNamed:@"customNavBarImage.png"];
// [self setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
[self setBackgroundColor:[UIColor colorWithPatternImage:image]];
[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
NSLog(@"Does this get called?"); //no
}
return self;
}
I don’t see any output on the console.
Instead I have done this to customize the UINavBar, but I feel like it isn’t as correct as sublassing it. In my first view’s viewDidLoad I added this line:
- (void)viewDidLoad
{
[super viewDidLoad];
if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
UIImage *image = [UIImage imageNamed:@"customNavBarImage.png"];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}
}
I agree with Ryan Perry. In addition to his answer:
You should not put this code in
initWithFrame, instead put your code inawakeFromNib