向UINavigationController添加按钮的问题

时间:2013-08-22 20:45:51

标签: ios objective-c cocoa-touch uinavigationcontroller

这就是我制作导航栏的方式:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UINavigationController *navBar = [[UINavigationController alloc] init];
    [navBar willMoveToParentViewController:self];
    navBar.view.frame = CGRectMake(0, 0, 320, 44);
    [self.view addSubview:navBar.view];
    [self addChildViewController:navBar];
    [navBar didMoveToParentViewController:self];
    ...

我读过的每个地方都说这就是你添加按钮的方式:

UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithTitle:@"test" style:UIBarButtonItemStyleBordered target:self action:@selector(print_message:)];
self.navigationItem.rightBarButtonItem = button;
[button release];

但按钮未显示在导航栏上。这段代码有什么问题?

2 个答案:

答案 0 :(得分:3)

除非您正在构建自定义容器视图控制器(这是一件相对罕见的事情),否则您不应在内容控制器的-viewDidLoad中构建UINavigationController。虽然它将为您提供导航栏,但您的视图控制器父子关系将向后:您的内容控制器将包含导航控制器,而不是相反。

相反,您需要在应用启动过程的早期创建导航控制器 - 可能在您的应用程序委托中,或者如果您正在使用它,则可以在主故事板中创建。确保新的导航控制器将您的内容控制器作为其根控制器(通常通过-initWithRootViewController:)。然后,您的self.navigationItem配置将正常运行。

答案 1 :(得分:1)

您应该以不同方式创建导航栏:

在xxxAppDelegate.m中编辑此方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.

//This is the ViewController of the view you want to be the root
xxxViewController *tvc = [[xxxViewController alloc]init];

//Now you have to initialize a UINavigationController and set its RootViewController
UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:tvc];

//Now set the RootViewController to the NavigationViewController
[[self window]setRootViewController:nvc];


self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}

所以现在你有了一个合适的NavigationController。如果在viewDidLoad方法中执行此操作,则每次重新加载视图时都会生成NavigationController。

现在在xxxViewController.m中编辑你的init方法:

- (id)init
{
...
if (self) {
 //Create a UINavigationItem
 UINavigationItem *n = [self navigationItem];

 //Create a new bar button item 
 UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithTitle:@"test"    style:UIBarButtonItemStyleBordered target:self action:@selector(print_message:)];
 [[self navigationItem]setRightBarButtonItem:button];
}
return self;
}

现在应该显示带有UIBarButtonItem的正确NavigationBar。