Sunday, 11 August 2013

Adding multiple buttons with spacing on UINavigation Bar programatically in iOS

This is the situation where we are unable to see the Navigation bar of UIViewController on storyboard...So to add the buttons on Navigation bar programatically as shown in following figure, we need the following code snippet.
    UIImage *image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"sync" ofType:@"png"]];

UIButton* addButtons = [UIButton buttonWithType:UIButtonTypeCustom];
[addButtons setBackgroundImage:image forState:UIControlStateNormal];
[addButtons setShowsTouchWhenHighlighted:YES];

addButtons.frame = CGRectMake(0,0, image.size.width, image.size.height);

[addButtons addTarget:self action:@selector(syncAction) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *addButtonBars = [[UIBarButtonItem alloc]initWithCustomView:addButtons];

UIImage *images = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"logout1" ofType:@"png"]];

UIButton* addButtons1 = [UIButton buttonWithType:UIButtonTypeCustom];
[addButtons1 setBackgroundImage:images forState:UIControlStateNormal];
[addButtons1 setShowsTouchWhenHighlighted:YES];

addButtons1.frame = CGRectMake(0,0, image.size.width, image.size.height);

[addButtons1 addTarget:self action:@selector(Logout11) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *logout = [[UIBarButtonItem alloc]initWithCustomView:addButtons1];

// Optional: if you want to add space between the sync & logout buttons
UIBarButtonItem *fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedSpaceBarButtonItem.width = 5;   

self.navigationItem.leftBarButtonItems =[logout,fixedSpaceBarButtonItem,addButtonBars];

No comments:

Post a Comment