Set a custom subclass of UINavigationBar in UINavigationController programmatically Set a custom subclass of UINavigationBar in UINavigationController programmatically objective-c objective-c

Set a custom subclass of UINavigationBar in UINavigationController programmatically


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

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


Since iOS5, apple provides a method to do this directly. Reference

UINavigationController *navigationController= [[UINavigationController alloc]initWithNavigationBarClass:[CustomNavBar class] toolbarClass:nil];[navigationController setViewControllers:[NSArray arrayWithObject:yourRootViewController]];


As of iOS 4, you can use the UINib class to help solve this issue.

  1. Create your custom UINavigationBar subclass.
  2. Create an empty xib, add a UINavigationController as the singleobject.
  3. Set the class for the UINavigationController's UINavigationBar to your custom subclass.
  4. Set your root view controller via one of these methods:
    • [navController setViewcontrollers[NSArray arrayWithObject:myRootVC]];
    • [navController pushViewController:myRootVC];

In code:

UINib *nib = [UINib nibWithNibName:@"YourCustomXib" bundle:nil];UINavigationController *navController =              [[nib instantiateWithOwner:nil options:nil] objectAtIndex:0];


Now you've got a UINavigationController with your custom UINavigationBar.