简体   繁体   中英

UINavigationBar - Set title programmatically?

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?

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.

Use

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

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

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

如果类是一种UIViewController,那么您可以在viewDidLoad方法中设置title。

    [self setTitle:@"My Title"];

In ViewDidLoad of your ViewController.m just write,

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

Here is the Output:

在此输入图像描述

Create IBOutlet of UINavigationBar

navigationBar.topItem.title = @"Title";

Hope this helps.

请注意,为了使标题显示AT ALL,导航控制器的委托必须设置为导航栏本身或标题永远不会显示!

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.

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

_title = @"Title";

or

self.title = @"Title";

试试这个,

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

I achieved this way in Swift 5

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

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