Friday, May 29, 2009

Creating a UIBarButtonItem programmatically

This counts as one of those things that I'll want to do again in the future but will have to re-research it by poring through old code or Googling (yet again). Sometimes for brevity, it isn't ideal to have a View Controller *and* a XIB for every little thing you want to present. The XIB is an extra file and the symbolic links to the controller can be a pain to maintain. To create your own action button (say, in the upper-right corner), use the following code:

- (void)viewDidLoad {
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:@"Load Colors"];
[navBar pushNavigationItem:navItem animated:NO];
UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"
navItem.rightBarButtonItem = editButton;

[self.view addSubview:navBar];

[editButton release];
[navItem release];
[navBar release];
[super viewDidLoad];

1 comment:

  1. Thanks Dean.
    Just the code snipped I needed to get out of a spot.
    Tim from Canberra