0
votes

I am presenting a new view table view controller as the root controller for a navigation controller. I then add a back button with a selector, but when I click the button nothing is called. I am only presenting it in a nav controller because i want to have the back button on the table view. Here is my code to show the controller:

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];

    ATDetailTableViewController *detailViewController = [sb instantiateViewControllerWithIdentifier:@"ATDetailTableViewController"];
    detailViewController.propToDisplay = self.apartments[0];
    detailViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:detailViewController];
    [self presentViewController:nav animated:YES completion:nil];

Then when the detailviewcontroller loads, i create the bar button item that does not call the selector method:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:nil
                                                                  action:@selector(backPressed)];
    self.navigationItem.leftBarButtonItem = backButton;
}

- (void)backPressed
{
    NSLog(@"back pressed...");
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

What is the best practice here? Should I just make a view controller with a toolbar? Also, I am getting the warning: Presenting view controllers on detached view controllers is discouraged

1
There's a complete answer below, but I'm just going to say that titling this button "Back" and calling it backButton is very misleading. It would be better to use either a standard Cancel and/or Done button using initWithBarButtonSystemItem:target:action Which one you would want to use largely depends on what the button and controller actually do. - David Berry

1 Answers

2
votes

The problem is that you set the target parameter to nil instead of self. You want:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                  style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(backPressed)];
    self.navigationItem.leftBarButtonItem = backButton;
}