我在一个视图中有一个导航栏,我希望能够通过编程来更改其导航项标题。
如何实现?
如何实现?
在你的UIViewController中
self.navigationItem.title = @"The title";
Swift 3 版本:
如果您在没有导航控制器的情况下使用导航栏,则可以尝试以下方法:
navigationBar.topItem?.title = "Your Title"
求助之希望。
在viewDidLoad中
self.title = @"Title";
viewDidLoad
中,或者更好的选择是写在initWithNibName:
下面。 self.navigationItem.title = @"title";
来自苹果文档:
最常用的使用导航栏的方法是使用导航控制器。您也可以将导航栏作为应用程序中的独立对象使用。
因此,如果您有一个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。
在你的UIViewController的viewDidLoad方法中
self.navigationItem.title = "The title"; //In swift 4
或者
你可以只
self.title = "The title"
这将会解决问题。
你还可以将上述语句放在应用程序委托中以实现全局复制。
您还可以使用
[self.navigationController.navigationBar.topItem setTitle:@"Titlet"];
self.title
更加精确。 - Robin Daugherty这段代码对我来说没有用
self.navigationItem.title = @"Title here";
self.title = "Title Name"
在 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";