简体   繁体   中英

iOS alertview action on a button

I have a button in a menu which when touched, pops up a alert message with two buttons: " Cancel " and " Yes ". This is the code I have for the alert:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game"
                                                message:@"Are you sure?"
                                               delegate:nil
                                      cancelButtonTitle:@"Cancel"
                                      otherButtonTitles:@"Yes", nil];
[alert show];

Is it possible to add an action to the button " Yes "?

In your code set the UIAlertView delegate:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil]; [alert show];

As you have set delegate to self, write the delegate function in the same class as shown below:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) { // Set buttonIndex == 0 to handel "Ok"/"Yes" button response
    // Cancel button response
    }}

You need to implement the UIAlertViewDelegate

and add the following...

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // do stuff
    }
}

Yes it is easy. See that argument called "delegate" that you have set to nil right now? Set that to an object... usually "self" if you are calling it from your view controller and then implement the selector for UIAlertViewDelegate.

You also need to declare that your view controller conforms to the UIAlertViewDelegate protocol. A good place to do this is in the "private" continuation class of the view controller.

@interface MyViewController() <UIAlertViewDelegate>
@end

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   NSLog(@"Button pushed: %d", buttonIndex);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM