Does anyone know how can I use my custom subclass of UINavigationBar
if I instantiate UINavigationController
programmatically (without IB)?
As of iOS 4, you can use the UINib
class to help solve this issue.
UINavigationBar
subclass.UINavigationController
as the single
object. UINavigationController
's UINavigationBar
to your custom subclass.[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
.
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]];
One scenario I've found that we need to use subclass rather than category is to set navigationbar backgroundcolor with pattern image, because in iOS5 overwriting drawRect using category does not work any more. If you want to support ios3.1-5.0, the only way you can do is to subclass navigationbar.
If you want to subclass navBar just to change background image - there is no need to in iOS 5. There will be method like this one setBackgroundImage
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];
}
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];