UINavigationBar - Set title programmatically?

喜夏-厌秋 提交于 2019-12-18 10:44:14

问题


I have a tab bar application with a different view on each tab. Each view has a UINavigationBar with title set on Interface Builder. I want to change the title based on a clause in the ViewDidLoad method, so if x { change the title }.

I have tried self.title = @"title", but this changes the title of the tab bar item itself.

So, how is this done?


回答1:


I've set the title programmatically using code something like this:

navBar.topItem.title = @"title";

where navBar is declared as an IBOutlet UINavigationBar linked to the navigation bar in interface builder. This worked in my app; however, I was not using a tab bar.

If navBar.topItem is the tab bar item, I don't see a way for you to change the title that appears on the navigation bar without also changing the title on the tab bar item, since the navBar's topItem and the tab bar item is the same object.




回答2:


Use

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

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




回答3:


Use this :

    CGRect navBarFrame = CGRectMake(0, 0, self.tableView.frame.size.width, 44.0);
    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:navBarFrame];

    UINavigationItem *navItem = [UINavigationItem alloc];
    navItem.title = @"Your Title";

    [navBar pushNavigationItem:navItem animated:false];

[self.view addSubView:navBar]; 

or

self.tableView.tableHeaderView = navBar; etc



回答4:


If the class is a type of UIViewController, then you can set title as given in the viewDidLoad method.

    [self setTitle:@"My Title"];



回答5:


In ViewDidLoad of your ViewController.m just write,

self.navigationItem.title=@"Hello World";

Here is the Output:




回答6:


Create IBOutlet of UINavigationBar

navigationBar.topItem.title = @"Title";

Hope this helps.




回答7:


I used the following:

self.navigationController.navigationBar.topItem.title = @"Title";

However, I also had to call it in a dispatch block as it wouldn't change the title when called within the viewDidLoad w/o it.




回答8:


Note that in order for the title to show up AT ALL the Navigation Controller's delegate MUST be set to the navigation bar itself or the title will NEVER show!




回答9:


You can also just set the title in the ViewDidLoad under your ViewController or TableViewController using

_title = @"Title";

or

self.title = @"Title";



回答10:


Try this,

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



回答11:


I achieved this way in Swift 5

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Title"
}


来源:https://stackoverflow.com/questions/3680805/uinavigationbar-set-title-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!