UINavigationBar - Set title programmatically?

2019-02-01 03:01发布

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?

10条回答
孤傲高冷的网名
2楼-- · 2019-02-01 03:42

Create IBOutlet of UINavigationBar

navigationBar.topItem.title = @"Title";

Hope this helps.

查看更多
等我变得足够好
3楼-- · 2019-02-01 03:42

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

_title = @"Title";

or

self.title = @"Title";
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-01 03:49

Try this,

self.navigationItem.title = @"Your title";
查看更多
何必那么认真
5楼-- · 2019-02-01 03:50

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.

查看更多
时光不老,我们不散
6楼-- · 2019-02-01 03:52

Use

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

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

查看更多
SAY GOODBYE
7楼-- · 2019-02-01 03:52

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.

查看更多
登录 后发表回答