[英]How to set the title of a Navigation Bar programmatically?
我在視圖中有一個導航欄,我想以編程方式更改其導航項標題。
這是怎么做到的?
在您的 UIViewController
self.navigationItem.title = @"The title";
Swift 3 版本:
如果你使用沒有導航的導航欄controller,那么你可以試試這個:
navigationBar.topItem?.title = "Your Title"
希望得到幫助。
在 viewDidLoad
self.title = @"Title";
來自蘋果文檔:
使用導航欄最常見的方法是使用導航 controller。 您還可以在應用程序中將導航欄用作獨立的 object。
因此,如果您有 UINavigationController,您需要做的就是設置導航欄的標題(如所有先前答案中所述)
self.navigationItem.title = @"title";
但是,如果您有一個獨立的導航欄,它是在 UIViewController 的 object 中以編程方式創建的,您必須通過創建適當的 UINavigationItem 對象並將它們添加到導航欄堆棧 ZA8CFDE63311C49EB2AC96B9666666666Fie 來設置導航欄的初始外觀
上述步驟的 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 版本的獨立導航欄,請查看此答案。
在viewDidLoad
中編寫以下代碼,或者在initWithNibName:
self.navigationItem.title = @"title";
謝謝。
你也可以使用
[self.navigationController.navigationBar.topItem setTitle:@"Titlet"];
在你的 UIViewController 的 viewDidLoad
self.navigationItem.title = "The title"; //In swift 4
或者
你可以
self.title = "The title"
會成功的
您還可以將上述語句放在應用程序委托中以進行全局復制。
這段代碼對我不起作用
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";
非常重要的注意事項:確保在父視圖控制器的 viewDidLoad 方法或 storyboard 中的父導航欄中進行上述更改
有時您可能會遇到更新標題但沒有產生任何影響的情況,這可能是當您在topItem
上有自定義視圖時,因此您可能希望像這樣更新它: (self.navigationController?.navigationBar.topItem?.titleView as? UILabel)?.text = "My Happy New Title"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.