iosobjective-cuiviewcontrolleruialertviewuialertviewdelegate

Push view programmatically from UIAlertView button?


I would open a UIViewController from a UIAlertView button but it doesn't work.

When user terminate a game I show a UIAlertView with some text and two buttons: "Ok" to dismiss alert and "Score" to open the score page.

This is the actual UIAlertView:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"YOU WIN!"
                                                            message:[NSString stringWithFormat:@"You win a game in %d seconds!",seconds]
                                                           delegate:self
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:@"Score", nil];
        [alert show];

and this is the code for push the view:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"Score"]){
        ScoreViewController *score = [[ScoreViewController alloc]init];
        [[self navigationController] pushViewController:score animated:YES];
    }
}

What I obtain is a completely black screen. Can someone help me? I can't figure it out what I'm doing wrong.

PS: ScoreViewController has a segue from the root view but of course I can't create a new one from storyboard because I want to perform segue programmatically, from the alert view button.

Hope I've been clear, any help will be very appreciate!


Solution

  • It looks like you're instantiating an instance of ScoreViewController and pushing onto your navigation controller. While this is a legitimate way of presenting another controller, it's different from performing a Storyboard segue.

    First, obviously, you'll have to make sure you have a segue connecting your view controllers in the Storyboard. It sounds like you've made it that far, so next you'll want to make sure the segue has an identifier. Select the segue and set its identifier in the Attributes inspector. Then perform the segue in code:

    [self performSegueWithIdentifier:@"YourIdentifier" sender:self];