UIAlertView buttons action code

2019-05-15 08:28发布

问题:

Do anyone know how to make actions for the buttons in UIAlertview? if so, please guide me.

回答1:

- (void)alertView:(UIAlertView *)alertView 
         didDismissWithButtonIndex:(NSInteger) buttonIndex 
{
    if (buttonIndex == 0)
    {
        NSLog(@"Cancel Tapped.");
    }
    else if (buttonIndex == 1) 
    {    
        NSLog(@"OK Tapped. Hello World!");
    }
}

Try This Code It Will Works for you...



回答2:

When buttons are clicked in UIAlertView, its delegate method

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

gets called. Your delegate must implement this method and check which button was pressed.

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            // Do something for button #1
            break;
        case 1:
            // Do something for button #2
            break;
        ...
    }
}

If you have multiple alert views, then you can differentiate them by their title as follows:

if ([alertView.title isEqualToString: yourAlertView.title]) {
    // proceed...
}


回答3:

Read the below article , will help you to understand the UIAlertViewDelegate.

iOS SDK: Working with UIAlertView and UIAlertViewDelegate



回答4:

Please use this code

First Set delegate for UIAlertView then write its delegate method as follows...

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
 {     
     if (buttonIndex == 0) {
        //Some Implementation
     } else if(buttonIndex == 1) {
        //Some Implementation
     }
 }


回答5:

If you want to get action for UIAlerView button.

You need to use UIAlertViewDelegate and its method for get action.

For Reference,

  • UIAlertViewDelegate