1
votes

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

2
Do you have any screenshots? When I set an image in IB it doesn't stretch it - Dan F
see edit. its really the ordering i want to be able to edit, so I have the ordering icon there. notice it gets stretched in IB. is the image just too largE? - user1337645
Hmm it looks like it is just being squashed, not stretched. Try resizing the icon texture to match what a bar button item expects. You can find all of the dimensions for varying icons in ios here - Dan F
Great!, worked. now for state, how do I swap out the image on click? I have another image for state on and off - user1337645

2 Answers

1
votes

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;
1
votes

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.)