IOS Beginner: UIAlertView window with 3 buttons> Check which button was clicked

I have a working code from a tutorial but donโ€™t understand it completely.

Situation:

After clicking a button in the iPhone app, AlertView with three buttons appears. Now I like to check which button the user clicked.

MANUAL CODE:

- (IBAction)infoButtonPressed:(id)sender { UIAlertView *myAlert1 = [[UIAlertView alloc]initWithTitle:@"My Alert View 1" message:@"Here we go" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Option1", @"Option2", nil]; [alert show]; } - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { NSLog(@"Button: %i, was pressed.", buttonIndex); } 

The code works, I see the correct output in the console as NSLog, but how is it possible that the method:

 - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { NSLog(@"Button: %i, was pressed.", buttonIndex); } 

refers to the correct presentation of the warning. In this case: myAlert1.

How about more than one view. For example, the second caller is myAlert2.

I know that the following code is incorrect, but it would be more useful for me if I write a method as follows:

 - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { NSLog(@"Button: %i, was pressed.", buttonIndex_FROM_myAlert1); } 

Hope you can help, drive me crazy.

Regards, Mark

+6
source share
1 answer

how is it possible that the method refers to the correct kind of warning?

For this reason, the delegate method alertView:didDismissWithButtonIndex: actually tells you what kind of view it refers to. Note that the method has two arguments. The second tells you the index of the button, and the first indicates the type of warning that this index refers to.

If you have multiple warnings that use the same delegate, you will need to check the first argument that warns about this. To be able to do this, you will need to store the alert views in ivar / property or another data structure in order to remember them in the delegate method. (Or, since UIAlertView is a subclass of UIView , you can use the tag property to distinguish between several views).

+8
source

Source: https://habr.com/ru/post/904804/


All Articles