Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: Adding Info button as right bar button item in navigation bar in code

Has anyone had any success creating an info button (italic 'i' in a circle) in code (read: without Interface Builder), and then assigning it as the right bar button item of a navigation bar?

I've looked everywhere, and I can't even find how to create an info button in code. Any help would be greatly appreciated.

like image 902
David Foster Avatar asked Aug 16 '10 10:08

David Foster


People also ask

How do I add a button to my navigation bar?

Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.


2 Answers

UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
like image 100
Reena Avatar answered Sep 17 '22 12:09

Reena


Here's a pretty good looking solution that I think covers all the points people brought up in the comments above. Similar to the accepted answer, but this approach includes extra spacing (via modifying the frame) so that the button isn't smashed up against the right edge.

// Create the info button
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];

// Adjust the frame by adding an addition 10 points to its width so the button is padded nicely
infoButton.frame = CGRectMake(infoButton.frame.origin.x, infoButton.frame.origin.y, infoButton.frame.size.width + 10.0, infoButton.frame.size.height);

// Hook the button up to an action
[infoButton addTarget:self action:@selector(showInfoScreen) forControlEvents:UIControlEventTouchUpInside];

// Add the button to the nav bar
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];

// Also make sure to add a showInfoScreen method to your class!
like image 33
Kyle Clegg Avatar answered Sep 16 '22 12:09

Kyle Clegg