Set a custom subclass of UINavigationBar in UINavigationController programmatically

Viewed 49897

Does anyone know how can I use my custom subclass of UINavigationBar if I instantiate UINavigationController programmatically (without IB)?

Drag a UINavigationController in IB show me an under Navigation Bar and using Identity Inspectory I can change class type and set my own subclass of UINavigationBar but programmatically I can't, navigationBar property of Navigation Controller is readonly...

What should I do to customize the navigation bar programmatically? Is IB more "powerful" than "code"? I believed all that can be done in IB could be done also programmatically.

12 Answers

You don't need to muck with the XIB simply use KVC.

[self.navigationController setValue:[[[CustomNavBar alloc]init] autorelease] forKeyPath:@"navigationBar"];

I use "option 1"

Create a nib-file with only the UINavigationController in it. And set the UINavigationBar Class to my custom Class.

self.navigationController = [[[NSBundle mainBundle] loadNibNamed:@"navigationbar" owner:self options:nil] lastObject];

[navigationController pushViewController:rootViewController animated:YES];

Further to obb64's comment, I ended up using his trick with setViewControllers:animated: to set the controller as the rootController for the navigationController loaded from the nib. Here's the code I'm using:

- (void) presentModalViewControllerForClass: (Class) a_class {
  UINavigationController *navController = [[[NSBundle mainBundle] loadNibNamed: @"CustomNavBar" owner:self options:nil] lastObject];

  LoginSignupBaseViewController *controller = [[a_class alloc] initWithNibName: nil bundle: nil];
  controller.navigationController = navController;
  [navController setViewControllers: A(controller) animated: NO];

  [self presentModalViewController: navController animated: YES];

  [controller release];
}
Related