我该如何在程序中设置UINavigation Bar的标题?

5
我该如何通过编程设置UINavigation Bar的标题?
4个回答

15
self.title = @"My View";
或者
navigationBar.topItem.title = @"My View";

根据您是否使用 UINavigationController


1
由于我没有使用UINavigationController,所以在创建了一个IBOutlet到navigationBar后,我使用了第二种语法。谢谢。 - jp chance

3

在UINavigationBar中显示的标题来自当前活动的UIViewController。

例如,假设我们想要一个带有名为MyCustomViewController的根视图控制器的UINavigationController。

在我们的应用程序委托中:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    UIViewController *myCustomViewController = [[MyCustomViewController alloc] init];
    navController = [[UINavigationController alloc] initWithRootViewController:myCustomViewController];
    [window addSubview:navController.view];
    [window makeKeyAndVisible];
}

在MyCustomViewController.m文件中:
- (void)viewDidLoad {
    self.title = @"Hello World!";
}

0

我成功地在视图控制器推送之前设置了标题。以下是我的代码:

    _chatTableViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ChatTableViewController"];
    _chatTableViewController.title = @"Live Chat";
    [[self navigationController]pushViewController:_chatTableViewController animated:YES];

0

在你的视图控制器实现文件中:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
     if(self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
             self.title = @"My Title";
     }
     return self;
}

这应该可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接