11

我有问题显示导航栏的rightBarButtonItem - 我试图在应用程序委托中创建它,我的UINavigationController设置。rightBarButtonItem不会出现在导航栏iOS

代码如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

// Override point for customization after application launch. 
RSCListViewController *list = [[RSCListViewController alloc] initWithStyle:UITableViewStylePlain]; 
self.navController = [[UINavigationController alloc] initWithRootViewController:list]; 

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:@"+" 
                   style:UIBarButtonItemStylePlain 
                  target:list 
                  action:@selector(addPressed:)]; 

self.navController.navigationItem.rightBarButtonItem = barButton; 

self.window.backgroundColor = [UIColor whiteColor]; 
[self.window makeKeyAndVisible]; 

[DatabaseManager openDatabase]; 

return YES; 
} 

运行应用程序,没有按钮项目出现在导航栏上。

我不确定我是否漏掉了一些明显的东西 - 我尝试使用相关的堆栈溢出线程纠正问题并没有取得任何成功。

任何帮助表示赞赏。

+0

一切显示正常? – Kyle

回答

29

您需要将您的酒吧按​​钮项目附加到您的自定义视图控制器,而不是导航控制器。从Updating the Navigation Bar

此外,导航控制器对象建立导航栏动态地使用具有上 导航堆栈的视图控制器相关联的导航项目(实例UINavigationItem类的 )的 内容。要更改导航栏的内容, 因此您必须为您的自定义视图 控制器配置导航项目。

(...)

导航控制器更新导航栏 右侧如下:

  • 如果新的顶层视图控制器具有自定义权限栏按钮项目,该项目被显示。要指定一个自定义右键栏按钮 项目,请设置视图控制器的 导航项目的rightBarButtonItem属性。

  • 如果未指定自定义右侧栏按钮项目,则导航栏在右侧栏上不显示任何内容。

因此,替换:

self.navController.navigationItem.rightBarButtonItem = barButton; 

有:

list.navigationItem.rightBarButtonItem = barButton; 
+0

谢谢 - 曾经假定显示在导航栏上的元素与导航控制器绑定,而不是堆栈顶部的视图...但是现在我考虑一下,导航栏没什么意义会因为显示哪个视图而经常改变。再次感谢您的帮助。 – Russell

+0

欢迎:) – albertamg

+0

由于某些原因,当您设置rightBarButtonItem的navigationItem为rootViewController时,VC无法正常工作:-(但是,正如您所说,只要具有@ navigationItem.rightBarButtonItem = whatever的vc就可以正常工作;“是尽管推到导航堆栈。 –