Search code examples
iphoneobjective-ciosuialertviewpushviewcontroller

Navigating between ViewControllers with UIAlertView


I'm trying to change view controllers based on a user's selection in a UIAlertView. I'm new to objective c and am having some trouble.

When the user presses "I'm done", i want the app to navigate back to the previous view controller. When the user presses "Scoreboard", i want the app to navigate to the next view controller.

UIAlertView *jigsawCompleteAlert = [[UIAlertView alloc]   //show alert box with option to play or exit
                                  initWithTitle: @"Congratulations!" 
                                  message:completedMessage 
                                  delegate:self 
                                  cancelButtonTitle:@"I'm done" 
                                  otherButtonTitles:@"Play again", @"Scoreboard",nil];
            [jigsawCompleteAlert show];

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"Cancel Tapped.");
        [self.navigationController popViewControllerAnimated:YES];

    }
    else if (buttonIndex == 1) {
        NSLog(@"GO tapped.");
        startDate = [NSDate date];
        // Create the stop watch timer that fires every 10 ms
        stopWatchTimer = [NSTimer 
                          scheduledTimerWithTimeInterval:1.0/10.0
                          target:self
                          selector:@selector(updateTimer)
                          userInfo:nil
                          repeats:YES];
    } else if (buttonIndex == 2) {
        NSLog(@"Scoreboard tapped.");
    }

}

The popView part is working, and the app navigates back one view controller. I don't know how to get the app to move forward one view controller. I know it's something to do with pushViewController but i've only seen quite old and contradictory articles detailing how to do this.

I'd appreciate some help with this, thanks.


Solution

  • You need to create new UIViewController and then push it to stack, something like this:

    else if (buttonIndex == 2) {
        NSLog(@"Scoreboard tapped.");
        MoreDetailViewController *ctrl = [[MoreDetailViewController alloc] initWithNibName:@"MoreDetailViewController" bundle:nil];
    
        [self.navigationController pushViewController:ctrl animated:YES];
    }    
    

    If you are using StoryBoard then provide identifier for your UIViewController in storyboard file (Attribute Inspector). enter image description here

    Put this code into handler:

    MoreDetailViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"MoreDetailViewController"];
    [self.navigationController pushViewController:vc animated:YES];