3

We used to use UIAlertViewDelegate in ViewController.h to make our custom Alert button to do an action, like pressing the Play Again button in the alert window makes the game restart.

How do we do this with UIAlertController, the replacement class for UIAlertView?

I read this document bellow provided by Apple and didn't see a delegate method mentioned. Does it mean we don't do that anymore?

https://developer.apple.com/reference/uikit/uialertcontroller

Jack Greenhill
  • 10,240
  • 12
  • 38
  • 70
Janmira
  • 41
  • 4

2 Answers2

2
  • First add UIAlertController

  • Then Add UIAlertAction

  • Then add that action to your alert controller.

like below.

UIAlertController *myalert = [UIAlertController alertControllerWithTitle:@"your title" message:@"your messate" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *myaction = [UIAlertAction actionWithTitle:@"you title" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //your action here
    }];


    [myalert addAction:myaction];
    [self presentViewController:myalert animated:YES completion:nil];
caldera.sac
  • 4,918
  • 7
  • 37
  • 69
0

As it sounds like you found out, UIAlertView is deprecated (beginning in iOS 8), and so is UIAlertViewDelegate.

You're supposed to use UIAlertController instead. UIAlertController uses a different method for handling user taps on buttons. In UIAlertController you add UIAlertAction objects to your alert controller.

A UIAlertAction takes a block of code that gets called when the user triggers that action. Instead of setting up a delegate that listens for messages in a protocol, you pass a handler block (closure) to each button action that you set up. It's a different way of solving the same problem.

@AnuradhS gave sample code showing hot to set it up.

Duncan C
  • 128,072
  • 22
  • 173
  • 272