heinst
heinst

Reputation: 8786

Nav Bar button loading random view before loading appropriate view

I have a back button on my answer view controller (a view controller that displays answers) if the user hits the back button I created it switches to a view that has the title of "Back" and just an empty tableview, before switching back to my main view of where all the questions to be answered are displayed. Why is this happening? Its a very brief thing, but definitely noticeable!

 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

Upvotes: 0

Views: 120

Answers (1)

Wain
Wain

Reputation: 119031

You're creating your own UINavigationBar and UINavigationItem instances and you probably shouldn't be. The situation you describe is exactly what a UINavigationController is for. When using a UINavigationController it creates the UINavigationBar and each UIViewController that you show on screen (push into the navigation controller) has its own UINavigationItem (with the title taken from the title of the view controller).

The reason you get an empty 'view' titled "Back" is that you're creating it:

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

Dispense with all of this, create a UINavigationController and make your question view controller it's root view controller, then add the navigation controller to the screen. Then when a question is answered, push the answer view controller:

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

Upvotes: 2

Related Questions