Back, Edit and Add buttons in navigation bar of TableView with Storyboard on iOS

16,724

Solution 1

First, the Apple docs say 'you do not add subviews to a navigation bar directly'. Don't know if this is enough to get the app bounced from the store, but it's not considered "proper".

Second, you can add more than three buttons to a UINavigationItem in iOS 5 but not in iOS 4 or earlier.

Finally, I'd leave the edit button top right and back top left. That's where people expect them. If I wanted an add button (and are on iOS 5), I'd place it next to the edit button.

Sorry; no help on storyboards. Don't know anything about them.

Solution 2

Incase anyone else should happen to stumble onto this question as well the solution is pretty easy. UINavigationItem has a property for rightItems wich is just an array of UIBarButtonItems. Put both an add button and an edit button into an array and assign it to rightItems and your done :-) And here is an example code snippet:

UITableViewController *table = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self     action:@selector(insertNewObject:)];
NSArray *barButtons = [NSArray arrayWithObjects:table.editButtonItem, addButton, nil];
table.navigationItem.rightBarButtonItems = barButtons;
Share:
16,724
yassassin
Author by

yassassin

Updated on June 04, 2022

Comments

  • yassassin
    yassassin almost 2 years

    I'm facing some problems in implementing a tableview, with "Back", "Edit" and "Add" buttons on the navigation bar. The tableview is reached by clicking on a row of another tableview, so the "Back" button is added automatically. With the storyboard I've added the "Add" button to the navigation bar. With code I've added the "Edit" button (I used code, since if I add the button with the storyboard, I don't know how to reproduce the "Edit" standard behavior...):

    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    

    The problem is that, in this way, the "Edit" button hides the "Back" button on the navigation bar.

    At this point, I've two questions:

    1. Is it possible with storyboard to add a third button on the navigation bar?
    2. In case I've to do this programmatically, I know that I can do this as follows:

      UIButton *button = [UIButton buttonWithType: UIButtonTypeRoundedRect];
      [button setFrame:CGRectMake(width-90,6,50,30)];
      [button setTitle:@"Edit" forState:UIControlStateNormal];
      button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
      [self.navigationController.navigationBar addSubview:button];
      

    But how can I implement via code the standard behavior of the "Edit" button? I mean, I click "Edit" and the button becomes "Done" and the rows become deletable...

    Thanks in advance, yassa