Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple UIAlertViews in the same view


I have two UIAlertViews with ok/cancel buttons.
I catch the user response by:

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

The question I'm having is, which alertView is currently open?
I have different actions to do when clicking ok/cancel on each one...

like image 961
Code Monkey Avatar asked Oct 04 '12 16:10

Code Monkey


2 Answers

You have several options:

  • Use ivars. When creating the alert view:

    myFirstAlertView = [[UIAlertView alloc] initWith...];
    [myFirstAlertView show];
    // similarly for the other alert view(s).
    

    And in the delegate method:

    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        if (alertView == myFirstAlertView) {
            // do something.
        } else if (alertView == mySecondAlertView) {
            // do something else.
        }
    }
    
  • Use the tag property of UIView:

    #define kFirstAlertViewTag 1
    #define kSecondAlertViewTag 2
    

    UIAlertView *firstAlertView = [[UIAlertView alloc] initWith...];
    firstAlertView.tag = kFirstAlertViewTag;
    [firstAlertView show];
    // similarly for the other alert view(s).
    

    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        switch (alertView.tag) {
            case kFirstAlertViewTag:
                // do something;
                break;
            case kSecondAlertViewTag:
                // do something else
                break;
        }
    }
    
  • Subclass UIAlertView and add a userInfo property. This way you can add an identifier to your alert views.

    @interface MyAlertView : UIAlertView
    @property (nonatomic) id userInfo;
    @end
    

    myFirstAlertView = [[MyAlertView alloc] initWith...];
    myFirstAlertView.userInfo = firstUserInfo;
    [myFirstAlertView show];
    // similarly for the other alert view(s).
    

    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        if (alertView.userInfo == firstUserInfo) {
            // do something.
        } else if (alertView.userInfo == secondUserInfo) {
            // do something else.
        }
    }
    
like image 190
DrummerB Avatar answered Nov 15 '22 13:11

DrummerB


UIAlertView is a UIView subclass so you can use its tag property for identification. So when you create alert view set its tag value and then you will be able to do the following:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
   if (alertView.tag == kFirstAlertTag){
      // First alert
   }
   if (alertView.tag == kSecondAlertTag){
      // First alert
   }
}
like image 38
Vladimir Avatar answered Nov 15 '22 13:11

Vladimir