user1337645
user1337645

Reputation: 473

adding custom BarButtonItem to top navigation bar

Using the interface builder in my storyboard, I put a Bar Button Item in the top left corner of my navigation toolbar that toggles the edit view of my table view cells. I currently have the text something like "Edit cells"

My question is, how do I change this to use an image? I created my own custom image for Edit Cells on state and Edit Cells off state, but when I specify the image in the interface builder, the image is stretched in the bar button item. Do I need to make this bar button item programmatically from code to make it use the frame of the image? How do I specify state?

I feel there should be a way to do this in the interface builder but I tried to do this programmatically:

UIImage *image = [UIImage imageNamed:@"edit-off.png"];
UIButton *showEditButton = [UIButton buttonWithType:UIButtonTypeCustom];
showEditButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );
[showEditButton setImage:image forState:UIControlStateNormal];
UIBarButtonItem *showEditButtonItem = [[UIBarButtonItem alloc] initWithCustomView:showEditButton];

Now how do I add showEditButtonItem to the top left of the navigation bar?

enter image description here

actual image:

enter image description here

Upvotes: 1

Views: 7026

Answers (2)

holex
holex

Reputation: 24041

add the button programatically is something like this:

UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"kyyL4.png"] style:UIBarButtonItemStylePlain target:self action:@selector(editObject:)];
self.navigationItem.rightBarButtonItem = editButton;

put this code into -viewDidLoad: method of your ViewController.m file.

(the sad news is the image will be stretched in this way as well.)

Upvotes: 1

Dan F
Dan F

Reputation: 17732

Icons in iOS are expected to be of a certain size. You can find all of the sizes of various icons you could want in the iOS Human Interface Guidelines.

As for setting it to different icons for different states, I believe you need to do that in code.

To set the image for a UIBarButtonItem you just need to set the image property:

editButton.image = editActiveImage;

or

editButton.image = editInactiveImage;

Upvotes: 1

Related Questions