Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Recipe: Building a Simple Two-Item Menu

Although many applications demand serious user interfaces, sometimes you don't need complexity. A simple one- or two-button menu can accomplish a lot in many iOS applications. Navigation controller applications easily lend themselves to a format where instead of pushing and popping children, their navigation bars can be used as basic menus. Use these steps to create a hand-built interface for simple utilities:

  1. Create a UIViewController subclass that you use to populate your primary interaction space.
  2. Allocate a navigation controller and assign an instance of your custom view controller to its root view.
  3. In the custom view controller, create one or two button items and add them to the view's navigation item.
  4. Build the callback routines that get triggered when a user taps a button.

Recipe 5-1 demonstrates these steps. It creates a simple view controller called TestBedViewController and assigns it as the root view for a UINavigationController. In the viewDidLoad method, two buttons populate the left and right custom slots for the view's navigation item. When tapped, these update the controller's title, indicating which button was pressed. This recipe is not feature rich, but it provides an easy-to-build two-item menu. Figure 5-1 shows the interface in action.

This code uses a handy bar-button-creation macro. When passed a title and a selector, this macro returns a properly initialized bar button item ready to be assigned to a navigation item. (Add autorelease to this macro if you're working in MRR code.)

#define BARBUTTON(TITLE, SELECTOR)     [[UIBarButtonItem alloc] initWithTitle:TITLE     style:UIBarButtonItemStylePlain target:self action:SELECTOR]

If you're looking for more complexity than two items can offer, consider having the buttons trigger UIActionSheet menus and popovers. Action sheets, which are discussed in Chapter 13, "Alerting the User," let users select actions from a short list of options (usually between two and five options, although longer scrolling sheets are possible) and can be seen in use in the Photos and Mail applications for sharing and filing data.

Recipe 5-1. Creating a Two-Item Menu Using a Navigation Controller

@implementation TestBedViewController
- (void) rightAction: (id) sender
{
    self.title = @"Pressed Right";
}

- (void) leftAction: (id) sender
{
    self.title = @"Pressed Left";
}

- (void) loadView
{
    [super loadView];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem =
        BARBUTTON(@"Right",@selector (rightAction:));
    self.navigationItem.leftBarButtonItem =
        BARBUTTON(@"Left", ));
}
@end
  • + Share This
  • 🔖 Save To Your Account