casillas
casillas

Reputation: 16793

Detect Alert Button Click Event

I have the following implementation to be reused entire app. I store the following code in the Utility.m class.

CustomViewController.m

How can I capture click event in the following

[self presentViewController:[Utility oneButtonDisplayAlert:@"Error" withMessage:@"Please try again later"] animated:YES completion:nil];

Utility.m

+ (UIAlertController *)oneButtonDisplayAlert : (NSString*)title withMessage : (NSString*) message
{
    UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:title
                                 message:message
                                 preferredStyle:UIAlertControllerStyleAlert];


    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"OK"
                                style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                    //Handle your yes please button action here
                                }];


    [alert addAction:yesButton];

    return alert;

}

Upvotes: 0

Views: 342

Answers (1)

rmaddy
rmaddy

Reputation: 318804

Add a block parameter to your oneButtonDisplayAlert:withMessage: method. Call that block inside the alert action's handler.

+ (UIAlertController *)oneButtonDisplayAlert:(NSString *)title withMessage:(NSString *)message andOKHandler:(void (^)(void))handler
{
    UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:title
                                 message:message
                                 preferredStyle:UIAlertControllerStyleAlert];


    UIAlertAction* yesButton = [UIAlertAction
                                actionWithTitle:@"OK"
                                style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                    if (handler) {
                                        handler();
                                    }
                                }];


    [alert addAction:yesButton];

    return alert;
}

And then call it as:

UIAlertController *alert = [Utility oneButtonDisplayAlert:@"Error" withMessage:@"Please try again later" andOKHandler:^{
    // whatever code you need when OK tapped
}];
[self presentViewController:alert animated:YES completion:nil];

Note: Code in this answer might have a typo. Syntax not verified.

Upvotes: 1

Related Questions