Friday, March 1, 2013

Using Toolbars in iPhone

The UINavigationController maintains a UIToolBar for each view controller in its stack. This toolbar is normally hidden, but we can place buttons on it and display it any time we want. Let’s see how this is done.

Start Xcode, select “Create a new Xcode project” and select the Empty Application template. Click Next, name the project ToolBarButtons, and choose options as shown:

Click Next, choose a location to save the project, and finally click Create. When the project has loaded, select the AppDelegate.m file, right-click that file, and select “New File” from the popup menu. (The reason we selected the AppDelegate.m file first is that Xcode will place newly created files immediately below the selected file in the navigator.)

Select the Objective-C class template, click Next, and name the class MainViewController. Make sure that the class is a subclass of UIViewController, and also create a XIB file for the controller’s view as shown:

Click Next, accept the default location, and click Create.

Now we’re going to set up a navigation controller having a MainViewController object as its root view controller. Select the AppDelegate.h file, and add the two properties for the UINavigationController and the MainViewController as shown:

#import <UIKit/UIKit.h>
#import "MainViewController.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navController;
@property (strong, nonatomic) MainViewController *rootViewController;

@end

Make sure that the MainViewController file is imported, otherwise we won’t be able to instantiate on object from it.
After adding the navController and rootViewController objects, Open the AppDelegate.m file, and make the following changes:

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize navController = _navController;
@synthesize rootViewController = _rootViewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.rootViewController = [[MainViewController alloc] initWithNibName:nil bundle:nil];
    self.rootViewController.title = @"Main View";
    self.navController = [[UINavigationController alloc] initWithRootViewController:self.rootViewController];
    [self.window addSubview:self.navController.view];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

As always, we first synthesize our properties. We’ve only shown the application: didFinishLaunchingWithOptions: method here, because it’s the only method we will be making changes to. Leave the remaining methods in place.

First, we allocate and initialize the rootViewController. The nib name of nil in this case directs the compiler to associate this controller with the XIB file that was created with it (MainViewController.xib). A bundle of nil directs the compiler to use this application’s bundle. After we initialize this controller, we set its title to @”Main View.” This title will appear in the navigation bar for this view controller.

Next, we set up the navController object. We make rootViewController this object’s Root View Controller. Adding the navController’s view to the main window as a subview, we then make the main window key and visible, and we’re off and running.

In the MainViewController.xib file, choose a nice color for the view:

Since the view controller’s title property was set to @”Main View” in the AppDelegate, that title will appear at the top of the interface when we run the app:

Open the MainViewController.m file, and make these additions to initWithNibName: bundle:

- ( id )initWithNibName : ( NSString * )nibNameOrNil bundle : ( NSBundle * )nibBundleOrNil
{
    self = [super initWithNibName :nibNameOrNil bundle :nibBundleOrNil ];
    if (self ) {
        // Custom initialization
       
        // set up the nav bar button:
        UIBarButtonItem *btnShow = [ [UIBarButtonItem alloc ]     initWithBarButtonSystemItem :UIBarButtonSystemItemSearch target :self     action : @selector (toggleToolBar ) ];
        self.navigationItem.rightBarButtonItems = [ NSArray arrayWithObjects :btnShow, nil ];
       
        // set up the tool bar buttons:
        UIBarButtonItem *btnRed = [ [UIBarButtonItem alloc ] initWithTitle : @ "Red"         style :UIBarButtonItemStyleDone target :self action : @selector (btnRedTouched ) ];
        UIBarButtonItem *btnBlue = [ [UIBarButtonItem alloc ] initWithTitle : @ "Blue"       style :UIBarButtonItemStyleDone target :self action : @selector (btnBlueTouched ) ];
        UIBarButtonItem *spacer = [ [UIBarButtonItem alloc ]      initWithBarButtonSystemItem :UIBarButtonSystemItemFlexibleSpace target : nil action : nil ];
        UIBarButtonItem *btnGreen = [ [UIBarButtonItem alloc ] initWithTitle : @ "Green"     style :UIBarButtonItemStyleDone target :self action : @selector (btnGreenTouched ) ];
        self.toolbarItems = [ NSArray arrayWithObjects :btnRed, btnBlue, spacer, btnGreen, nil ];
       
    }
    return self;
}

First, we add a UIBarButtonSystemItemSearch button to the navigationItem’s rightBarButtonItems array. This button will be placed at the right of the top navigation bar. Next, we set up three bar buttons (btnRed, btnBlue, and btnGreen) and a spacer. The three buttons each have a selector, these will be defined shortly. Each also is initialized with a title, and a style of UIBarButtonItemStyleDone, which will produce a button with a blue background and white bolded text.

The function of the spacer is to add “flexible space” between btnBlue and btnGreen. Flexible space will act as a “spring” between the two buttons, pushing btnGreen all the way to the right of the tool bar. Since this space is invisible, it makes no sense to assign it an action method, so we have set both the target and action of this object to nil.

Now that we have the buttons, we need to add them to the tool bar. Each view controller has it’s own toolBarItems property, which is an NSArray of UIBarButtonItem objects. This line:

self.toolbarItems = [ NSArray arrayWithObjects :btnRed, btnBlue, spacer, btnGreen, nil ];

stuffs the toolBarButtons array with the three buttons and the spacer.

All that remains now is to implement the four methods we set as actions in the buttons:

- ( void )toggleToolBar
{
    BOOL barState = self.navigationController.toolbarHidden;
    [self.navigationController setToolbarHidden :!barState animated : YES ];
}

- (void)btnRedTouched
{
    self.view.backgroundColor = [UIColor redColor];
}

- (void)btnBlueTouched
{
    self.view.backgroundColor = [UIColor cyanColor];
}

- (void)btnGreenTouched
{
    self.view.backgroundColor = [UIColor greenColor];
}

toggleToolBar gets the hidden property of the tool bar, then sets that property to its negation. In other words, if the tool bar is hidden it will be shown, if it is shown it will be hidden.

The three btn…Touched methods set the color of the view’s background to red, cyan, or green when they are touched.
Run the app, and enjoy:


Source : edumobile[dot]org

0 comments:

Post a Comment