简体   繁体   中英

UINavigationBar not displaying title in iOS

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];

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.

Use

self.navigationItem.title = @"the title";

as setting navBar.topItem.title will not work in all circumstances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM