Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a custom subclass of UINavigationBar in UINavigationController programmatically

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.

like image 535
Duccio Avatar asked Dec 08 '09 19:12

Duccio


3 Answers

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

[self.navigationController setValue:[[[CustomNavBar alloc]init] autorelease] forKeyPath:@"navigationBar"];
like image 100
Fred Avatar answered Nov 08 '22 00:11

Fred


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]];
like image 67
Pascalius Avatar answered Nov 08 '22 00:11

Pascalius


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 single object.
  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.

like image 37
gorbster Avatar answered Nov 07 '22 23:11

gorbster