Sunday, June 9, 2013

UINavigationItem setLeftBarButtonItem example in Objective C (iOS).


UINavigationItem setLeftBarButtonItem

Sets the custom bar button item, optionally animating the transition to the new item.

- (void)setLeftBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated

Parameters[UINavigationItem setLeftBarButtonItem]
item
A custom bar item to display on the left side of the navigation bar.
animated
Specify YES to animate the transition to the custom bar item when this item is the top item. Specify NO to set the item immediately without animating the change.

Discussion of [UINavigationItem setLeftBarButtonItem]
If two navigation items have the same custom left or right bar button items, those bar button items remain stationary during the transition when the navigation item is pushed or popped.

UINavigationItem setLeftBarButtonItem example.
[super viewDidLoad];
    _navBar = [[UINavigationBar alloc] init];
    [_navBar setFrame:CGRectMake(0,0,self.view.bounds.size.width,52)];
    [self.view addSubview:_navBar];
    UINavigationItem *navItem = [[UINavigationItem alloc]initWithTitle:@""];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(buttonSettingClicked)];
    [navItem setLeftBarButtonItem:barButton];

    [_navBar setItems:@[navItem]];

Example of [UINavigationItem setLeftBarButtonItem].
UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(theEditMethod:)];     
[viewController.navigationItem setLeftBarButtonItem:leftBarButton animated:NO];
[leftBarButton release];

UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(theAddMethod:)];      
[viewController.navigationItem setRightBarButtonItem:rightBarButton animated:NO];
[rightBarButton release];

UINavigationItem setLeftBarButtonItem example.
Assuming iOS 5 onwards add your custom buttons:

[self.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects: customBarItem, customBarItemSetting, nil] animated:NO];

End of UINavigationItem setLeftBarButtonItem example article.