2
votes

I'm having some strange difficulties with setting a title and adding a bar button to my navigation bar.

My app is a Tabbed application. The problem is within my first tab. The first tab consists of a UINavigationController, that contains a UITableViewController. From my AppDelegate:

UIViewController *firstViewController = [[MyTableViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:firstViewController];

_tabBarController = [[TFTabBarController alloc] init];
_tabBarController.delegate = self;
_tabBarController.viewControllers = [NSArray arrayWithObjects:navigationController, nil];

On selecting a row in firstViewController, I push a UIWebViewController on the navigation stack:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIViewController *secondViewController = [[MyWebViewController alloc] init];
    [self.navigationController pushViewController:secondViewController animated:YES];
}

On intercepting the onclick of a hyperlink in the WebView, I push another UITableView on the navigation stack:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        UIViewController *thirdViewController = [[MyTableViewController alloc] init];
        [self.navigationController pushViewController:thirdViewController animated:YES];

        return NO;
    }
    return YES;
}

As thirdViewController opens, its navigation bar only contains the back button with the title of the previous view to navigate back. Its title and the right bar button are not shown...

This is how I try to display them:

self.title = @"My Title";

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Push me" style:UIBarButtonItemStylePlain target:self action:@selector(push)];

I also tried setting the button through the navigationController, but still no luck:

self.navigationController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Push me" style:UIBarButtonItemStylePlain target:self action:@selector(push)];

What could I be doing wrong here?

1

1 Answers

0
votes

Check that self.navigationItem and self.navigationController are not nil when accessed.

From the documentation:

The first time the property is accessed, the UINavigationItem object is created. Therefore, you shouldn’t access this property if you are not using a navigation controller to display the view controller.

A good place to access these members is under -viewDidLoad and not upon initialization.