导航栏按钮在加载适当视图之前加载随机视图

时间:2013-05-13 22:22:27

标签: iphone objective-c uinavigationbar back

我的答案视图控制器上有一个后退按钮(一个显示答案的视图控制器)如果用户点击我创建的后退按钮,它会切换到标题为“后退”的视图,只是一个空的桌面视图切换回我的主要视图,显示要回答的所有问题。为什么会这样?这是一个非常简短的事情,但绝对引人注目!

 UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 48)];
navBar.delegate = self;
UINavigationItem *backItem = [[UINavigationItem alloc] initWithTitle:@"Back"];
[navBar pushNavigationItem:backItem animated:NO];

UINavigationItem *topItem = [[UINavigationItem alloc] initWithTitle:@"Question"];
[navBar pushNavigationItem:topItem animated:NO];
topItem.leftBarButtonItem = nil;

[self.view addSubview:navBar];


- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{

   ViewController *controller = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
   controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
   [self presentViewController:controller animated:YES completion:nil];
   return true;
}

- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item
{

   ViewController *controller = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
   controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
   [self presentViewController:controller animated:YES completion:nil];
}

Picture of view with back button Picture of problem that is occurring

1 个答案:

答案 0 :(得分:2)

您正在创建自己的UINavigationBarUINavigationItem个实例,而您可能不应该这样做。您描述的情况正是UINavigationController的用途。使用UINavigationController时,它会创建UINavigationBar,并且您在屏幕上显示的每个UIViewController(推入导航控制器)都有自己的UINavigationItem(标题取自视图控制器的title

您获得标题为“返回”的空“视图”的原因是您正在创建它:

UINavigationItem *backItem = [[UINavigationItem alloc] initWithTitle:@"Back"];
[navBar pushNavigationItem:backItem animated:NO];

分配所有这些,创建一个UINavigationController并使你的问题视图控制器它的根视图控制器,然后将导航控制器添加到屏幕。然后当问题得到解答时,按下答案视图控制器:

[self.navigationController pushViewController:answerViewController animated:YES];