Sunday, June 9, 2013

UINavigationItem initWithTitle example in Objective C (iOS).


UINavigationItem initWithTitle

Returns a navigation item initialized with the specified title.

- (id)initWithTitle:(NSString *)title

Parameters
title
The string to set as the navigation item’s title displayed in the center of the navigation bar.

Return Value
A new UINavigationItem object initialized with the specified title.

Discussion of [UINavigationItem initWithTitle]
This is the designated initializer for this class.

UINavigationItem initWithTitle example.
- (void)loadView
{
    self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.view.backgroundColor = [UIColor redColor];
    self.title = @"MainVC";

    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"SecondLevel" style:UIBarButtonItemStyleBordered target:self action:@selector(secondLevelSelected:)];
    self.navigationItem.rightBarButtonItem = rightButton;
}

- (void) secondLevelSelected:(id)sender
{
    SecondVC *secondVC = [[SecondVC alloc]  init];
    [self.navigationController pushViewController:secondVC animated:YES];
}

Example of [UINavigationItem initWithTitle].
- (void)loadView
{
    self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 240)];
    self.view.backgroundColor = [UIColor greenColor];
    self.title = @"SecondVC";

    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithTitle:@"FirstLevel" style:UIBarButtonItemStyleBordered target:self action:@selector(leftBtnSelected:)];
    self.navigationItem.leftBarButtonItem = leftBtn;
}

- (void) leftBtnSelected:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

UINavigationItem initWithTitle example.
// in .h file
@property (nonatomic, retain) UINavigationBar *navBar;

// in .m file just below @implementation
@synthesize navBar;

// within .m method
navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];
navBar.barStyle = UIBarStyleBlack;

UINavigationItem *title = [[UINavigationItem alloc] initWithTitle:@"Nav Bar Title"];

UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]
                       initWithTitle:@"Back"
                               style:UIBarButtonItemStylePlain
                              target:nil
                              action:@selector(backButtonSelected:)];

title.leftBarButtonItem = leftButton;

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]
         initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                              target:nil
                              action:@selector(showActionSheet:)];

title.rightBarButtonItem = rightButton;

[navBar pushNavigationItem:title animated:YES];

[self.view addSubview:navBar];

End of UINavigationItem initWithTitle example article.