Bar button items side by side
Time to move on to actual programming. I will try to cover questions I once looked up answers to myself and later used in practice.
Here is a task that comes up often in practice: you need to place several bar button items side by side. For example, in my app “Contests, Games & Raffles” there are 4 buttons at the top: increase font size, decrease font size, share with friends, and add to favorites.
As it turned out, Apple knows better than us how many buttons we need on each side โ and Interface Builder will not let you do it. You can only place one button on the right, one on the left, and one in the middle on a storyboard scene. So it has to be done in code.
The code goes into viewDidLoad and looks like this:
// Create an image object for the "Favorites" button
UIImage *Favorites_add = [UIImage imageNamed:@"favorites_add.png"];
UIBarButtonItem *addFavoritesItem = [[UIBarButtonItem alloc] initWithImage:Favorites_add
style:UIBarButtonItemStylePlain target:self action:@selector(addFavorites)];
// Almost the same, but we take the standard Action image,
// so there is no need to create a custom image for this button.
UIBarButtonItem *sendSocialItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAction
target:self action:@selector(sendSocial)];
// All the other buttons use our own images, added to the project in advance
UIImage *Font_minus = [UIImage imageNamed:@"font_down.png"];
UIBarButtonItem *fontMinusItem = [[UIBarButtonItem alloc] initWithImage:Font_minus
style:UIBarButtonItemStylePlain target:self action:@selector(fontChanges:)];
UIImage *Font_plus = [UIImage imageNamed:@"font_up.png"];
UIBarButtonItem *fontPlusItem = [[UIBarButtonItem alloc] initWithImage:Font_plus
style:UIBarButtonItemStylePlain target:self action:@selector(fontChanges:)];
The array of our buttons:
NSArray *actionButtonItems = @[ sendSocialItem, addFavoritesItem, fontMinusItem, fontPlusItem ];
// Assign our array to the rightBarButtonItems property โ
// and instead of one button on the right there are now 4
self.navigationItem.rightBarButtonItems = actionButtonItems;
Now, how do we make the buttons actually do something? Let’s look at the “Favorites” button as an example โ the rest work the same way.
When we created the button, we wrote:
target:self action:@selector(addFavorites)];
That means this class must contain a method named addFavorites where the action is defined. For example:
-(void)addFavorites
self.labelName.text = @"The button was pressed";
