Sunday, June 9, 2013

UINavigationItem leftBarButtonItems example in Objective C (iOS).


UINavigationItem leftBarButtonItems

An array of custom bar button items to display on the left side of the navigation bar when the receiver is the top navigation item.

@property(nonatomic, copy) NSArray *leftBarButtonItems

Discussion of [UINavigationItem leftBarButtonItems]
This array can contain 0 or more bar items to display on the left side of the navigation bar. Items can include fixed-width and flexible-width spaces. If the leftItemsSupplementBackButton property is YES, the items are displayed to the right of the back button, otherwise the items replace the back button and start at the left edge of the bar. Items are displayed left-to-right in the same order as they appear in the array.[UINavigationItem leftBarButtonItems]

If there is not enough room to display all of the items in the array, those that would overlap the title view (if present) or the buttons on the right side of the bar are not displayed.

The first item in the array can also be set using the leftBarButtonItem property.

UINavigationItem leftBarButtonItems example.
You need to add UIBarButtonItem instance to a UINavigationItem, not to a UINavigationBar. So you can do this as:

NSArray *buttonArray = [NSArray arrayWithObjects:logoButton, logoButton2, logoButton3, nil];
self.navigationItem.leftBarButtonItems = buttonArray;
If you want your buttons on the right, use rightBarButtonItems.

Example of [UINavigationItem leftBarButtonItems].
UIBarButtonItem *backButtonItem // Assume this exists, filled with our custom view

// Create a negative spacer to go to the left of our custom back button,
// and pull it right to the edge:
UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
    target:nil action:nil];
negativeSpacer.width = -5;
// Note: We use 5 above b/c that's how many pixels of padding iOS seems to add

// Add the two buttons together on the left:
self.navigationItem.leftBarButtonItems = [NSArray
    arrayWithObjects:negativeSpacer, backButtonItem, nil];

UINavigationItem leftBarButtonItems example.
m_navBar = [[UINavigationBar alloc] init];
  [m_navBar setFrame:CGRectMake(0,0,self.view.bounds.size.width,52)];
  [self.view addSubview:m_navBar];

  UIBarButtonItem *barButton = [[UIBarButtonItem alloc]
                                initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                target:self
                                action:@selector(buttonSettingClicked)];

  UINavigationItem* navItem = [[UINavigationItem alloc] initWithTitle:@"MyItem"];
  [m_navBar pushNavigationItem:navItem animated:NO];

  navItem.leftBarButtonItems = @[barButton, barButton];

End of UINavigationItem leftBarButtonItems example article.