Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add 2 buttons into the UINavigationbar on the right side without IB?

How can I add 2 buttons into the UINavigationBar without XIB?
The 2 buttons should be aligned on the right side of the UINavigationBar.

I know how I can add one button, but how about two?

like image 489
Alexander Avatar asked Nov 26 '09 13:11

Alexander


2 Answers

With iOS 5+ it's as easy as:

UIBarButtonItem *btnShare = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(share)]; UIBarButtonItem *btnRefresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)]; [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:btnShare, btnRefresh, nil]]; 
like image 197
domsom Avatar answered Sep 21 '22 20:09

domsom


I posted code (see below) to add two buttons to the right of the navigationBar. You can set barStyle = -1 instead of subclassing UIToolbar.

UIToolbar *tools = [[UIToolbar alloc]                     initWithFrame:CGRectMake(0.0f, 0.0f, 103.0f, 44.01f)]; // 44.01 shifts it up 1px for some reason tools.clearsContextBeforeDrawing = NO; tools.clipsToBounds = NO; tools.tintColor = [UIColor colorWithWhite:0.305f alpha:0.0f]; // closest I could get by eye to black, translucent style.                                                               // anyone know how to get it perfect? tools.barStyle = -1; // clear background NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:3];  // Create a standard refresh button. UIBarButtonItem *bi = [[UIBarButtonItem alloc]     initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh:)]; [buttons addObject:bi]; [bi release];  // Create a spacer. bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; bi.width = 12.0f; [buttons addObject:bi]; [bi release];  // Add profile button. bi = [[UIBarButtonItem alloc] initWithTitle:@"Profile" style:UIBarButtonItemStylePlain target:self action:@selector(goToProfile)]; bi.style = UIBarButtonItemStyleBordered; [buttons addObject:bi]; [bi release];  // Add buttons to toolbar and toolbar to nav bar. [tools setItems:buttons animated:NO]; [buttons release]; UIBarButtonItem *twoButtons = [[UIBarButtonItem alloc] initWithCustomView:tools]; [tools release]; self.navigationItem.rightBarButtonItem = twoButtons; [twoButtons release]; 
like image 29
ma11hew28 Avatar answered Sep 21 '22 20:09

ma11hew28