我在视图中有一个导航栏,我想以编程方式更改其导航项目标题。
这是怎么做到的?
答案 0 :(得分:178)
在你的UIViewController
中self.navigationItem.title = @"The title";
答案 1 :(得分:20)
Swift 3版本:
如果您使用不带导航控制器的导航栏,则可以尝试:
navigationBar.topItem?.title = "Your Title"
希望得到帮助。
答案 2 :(得分:10)
在viewDidLoad
中 self.title = @"Title";
答案 3 :(得分:7)
使用导航栏最常用的方法是使用导航 控制器。您还可以使用导航栏作为独立对象 在你的应用程序中。
所以如果您有一个UINavigationController,那么您需要做的就是设置导航栏的标题(如之前的所有答案中所述)
self.navigationItem.title = @"title";
但是如果你有一个在UIViewController的对象中以编程方式创建的独立导航栏,你必须通过创建适当的UINavigationItem对象并将它们添加到导航栏对象堆栈来设置导航栏的初始外观,即
上述步骤的Objective-C代码示例:
UINavigationBar* navbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
/* Create navigation item object & set the title of navigation bar. */
UINavigationItem* navItem = [[UINavigationItem alloc] initWithTitle:self.shoppingItem.name];
/* Create left button item. */
UIBarButtonItem* cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onTapCancel:)];
navItem.leftBarButtonItem = cancelBtn;
/* Create left button item. */
UIBarButtonItem* doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onTapDone:)];
navItem.rightBarButtonItem = doneBtn;
/* Assign the navigation item to the navigation bar.*/
[navbar setItems:@[navItem]];
/* add navigation bar to the root view.*/
[self.view addSubview:navbar];
对于Swift版本的独立导航栏,请查看this answer。
答案 4 :(得分:6)
在viewDidLoad
中写下以下代码,或者更好的是initWithNibName:
self.navigationItem.title = @"title";
感谢。
答案 5 :(得分:5)
You can also use
[self.navigationController.navigationBar.topItem setTitle:@"Titlet"];
答案 6 :(得分:1)
此代码对我不起作用
self.navigationItem.title = @"Title here";
但这很有效。
self.title = "Title Name"
答案 7 :(得分:0)
在ViewDidLoad方法
中使用它格式:
@property(nonatomic,readonly,retain) UINavigationItem *navigationItem; // Created on-demand so that a view controller may customize its navigation appearance.
示例:
self.navigationItem.title = @"Title here";
答案 8 :(得分:0)
非常重要的注意事项:确保在父视图控制器的viewDidLoad方法或故事板中的父级导航栏中进行上述更改
答案 9 :(得分:0)
有时您可能会遇到更新标题并且不会产生任何影响的情况,这可能是您在topItem
上有自定义视图时因此您可能希望像这样更新它:{ {1}}
答案 10 :(得分:0)
在您的UIViewController的viewDidLoad
self.navigationItem.title = "The title";//In swift 4
会成功的
您还可以将以上语句放入应用程序委托中以进行全局复制。