您应该以不同的方式创建导航栏:
在您的 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。