如何以编程方式设置导航栏的标题?

问题描述 投票:0回答:12

我的视图中有一个导航栏,我想以编程方式更改其导航项标题。

这是如何做到的?

ios iphone view uinavigationbar
12个回答
227
投票

在你的 UIViewController 中

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

34
投票

Swift 3 版本:

如果您使用没有导航控制器的导航栏,那么您可以尝试以下操作:

navigationBar.topItem?.title = "Your Title"

希望得到帮助。


11
投票

在viewDidLoad中

  self.title = @"Title";

7
投票

viewDidLoad
中写入以下代码,或者在
initWithNibName:

下可能会更好
  self.navigationItem.title = @"title";

谢谢。


7
投票

来自 Apple 文档

使用导航栏最常见的方式是使用导航栏 控制器。您还可以将导航栏用作独立对象 在您的应用程序中。

因此,如果您有 UINavigationController,则需要执行所有操作来设置导航栏的标题(如之前所有答案中所述)

self.navigationItem.title = @"title";

但是,如果您有一个在 UIViewController 对象内以编程方式创建的独立导航栏,则必须通过创建适当的 UINavigationItem 对象并将它们添加到导航栏对象堆栈中来设置导航栏的初始外观,即

  1. 创建导航栏(UINavigationBar)实例
  2. 创建导航栏项 (UINavigationItem) 的实例,用于管理要在 UINavigationBar 对象中显示的按钮和视图。请注意,您在此步骤设置了标题。
  3. (可选步骤)向导航栏项目添加右/左按钮(UIBarButtonItem 的实例)。

上述步骤的 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 版本,请查看 这个答案


6
投票

您也可以使用👇🏻

[self.navigationController.navigationBar.topItem setTitle:@"Titlet"];

6
投票

在你的 UIViewController 的 viewDidLoad 中

self.navigationItem.title = "The title";  //In swift 4

你可以

self.title = "The title"

会成功的

您也可以将上述语句放在应用程序委托中以进行全局复制。


3
投票

此代码对我不起作用

self.navigationItem.title = @"Title here";

但这有效。

self.title = "Title Name"

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";

0
投票

非常重要的注意事项:确保在父视图控制器的 viewDidLoad 方法或故事板中的父导航栏中进行上述更改


0
投票

有时您可能会遇到这样的情况:您正在更新标题,但它没有造成任何效果,这可能是当您在

topItem
上有自定义视图时,因此您可能需要像这样更新它:
(self.navigationController?.navigationBar.topItem?.titleView as? UILabel)?.text = "My Happy New Title"


0
投票

斯威夫特:

self.navigationItem.title = "The title;

目标c

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

SwiftUI

.navigationBarTitle("Your Title Here")
© www.soinside.com 2019 - 2024. All rights reserved.