Can't assign multiple Buttons to UINavigationItem when using Storyboard with iOS 5

user810395 picture user810395 · Mar 27, 2012 · Viewed 13.7k times · Source

I'm a iOS developer with a lot experience in developing the UI by code.

I'm now testing the Storyboard functionality, because I testing to switch to "design" the UI rather then implementing it. In the past I stuck with to much limits using nib/xib's and therefore I never succeed with the switch. So here comes a new try with storyboading :)

Now my question - I'm designing an iPad Storyboard which has a Navigation Controller and a Tableview Controller. I want to add multiple UIBarButtonItems, but I can just add one for each side with the Interface Builder.

The code would look like:

UIBarButtonItem *b = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:nil action:nil];

UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
spacer.width = 20;

self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:self.editButtonItem, spacer, b, nil];

But why can't I add multiple buttons using the IB? There are only outlets for leftBarButtonItem, rightBarButtonItems, backBarButtonItems...

This is driving me crazy¡¡¡

Thanks!

Answer

Shimanski Artem picture Shimanski Artem · Dec 6, 2013

I found an easy solution.

1) Add the folowing category:

@interface UINavigationItem(MultipleButtonsAddition)
@property (nonatomic, strong) IBOutletCollection(UIBarButtonItem) NSArray* rightBarButtonItemsCollection;
@property (nonatomic, strong) IBOutletCollection(UIBarButtonItem) NSArray* leftBarButtonItemsCollection;
@end

@implementation UINavigationItem(MultipleButtonsAddition)

- (void) setRightBarButtonItemsCollection:(NSArray *)rightBarButtonItemsCollection {
    self.rightBarButtonItems = [rightBarButtonItemsCollection sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"tag" ascending:YES]]];
}

- (void) setLeftBarButtonItemsCollection:(NSArray *)leftBarButtonItemsCollection {
    self.leftBarButtonItems = [leftBarButtonItemsCollection sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"tag" ascending:YES]]];
}

- (NSArray*) rightBarButtonItemsCollection {
    return self.rightBarButtonItems;
}

- (NSArray*) leftBarButtonItemsCollection {
    return self.leftBarButtonItems;
}

@end

2) Add your items to view controller (items will be sorted ascending by tag)

enter image description here

3) Connect your items with leftBarButtonItemsCollection or rightBarButtonItemsCollection outlet collection of UINavigationItem

enter image description here