Reputation: 1484
Trying to set a NavBar programaticaly, and my title isn't showing in the navbar. Any ideas as to whats happening?
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
navbar.topItem.title = @"My accounts";
[self.view addSubview:navbar];
Upvotes: 1
Views: 1659
Reputation: 23624
The problem here is your use of the UINavigationBar
.
Read the documentation for UINavigationController
programming here.
You should not be creating your own UINavigationBar
and adding it as a subview to your view controller's view.
The correct thing to do is to create a UINavigationController
and add your view controller to its stack.
So something like this:
CustomViewController *myViewController = ...// whatever initialization you do
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myViewController];
Each view controller has its own UINavigationItem
that the navigation controller uses to set up the navigation bar's view when that view controller is at the top of the stack.
So in your CustomViewController.m
, possibly in the init
method or in viewDidLoad
,
you can set up the navigation item by doing something like this:
self.navigationItem.title = @"whatever";
self.navigationItem.rightBarButtonItem = ...// create a UIBarButtonItem and set it here if you want a button on the right side of the navigation bar
So once again, you do not touch the navigation bar directly or add it to your view hierarchy. The UINavigationController
handles all of that for you.
Upvotes: 2
Reputation: 8090
Use
self.navigationItem.title = @"the title";
as setting navBar.topItem.title will not work in all circumstances.
Upvotes: 0