How to present UIAlertController from SKScene

后端 未结 3 1911
鱼传尺愫
鱼传尺愫 2021-01-22 23:01

I\'m working in Spritekit and I\'m trying to present a UIAlertController from my SKScene, but I am having trouble doing it. I\'ve watched several tutorials but none of the UIAle

3条回答
  •  礼貌的吻别
    2021-01-22 23:21

    SKScene shouldn't be the one presenting the UIAlertController, but rather a UIViewController such as your initial GameViewController. Above code works fine when called from a UIViewController.

    You could use NSNotificationCenter to help you call your view controller.

    Add this to your view controller's viewDidLoad method,

    [[NSNotificationCenter defaultCenter] addObserver:self                                          
                                             selector:@selector(playerLost:) 
                                                 name:@"PlayerLostNotification" 
                                               object:nil];   
    

    and you will need to define this method too.

    - (void)playerLost:(NSNotification*) notification {
       UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"You Lose!" 
                                             message:@"Do You Want To Beat This Level?" 
                                      preferredStyle:UIAlertControllerStyleAlert];
    
       UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"GiveUp"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * action) {
                              [alert dismissViewControllerAnimated:YES completion:nil];
                           }];
       [alert addAction:cancel];
       [self presentViewController:alert animated:YES completion:nil];
    }                             
    

    In your SKScene when the player loses,

    [[NSNotificationCenter defaultCenter] postNotificationName:@"PlayerLostNotification" object:self];
    

提交回复
热议问题