Multiple UIAlertViews in the same view

和自甴很熟 提交于 2019-12-06 04:39:26

问题



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...


回答1:


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.
        }
    }
    



回答2:


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
   }
}


来源:https://stackoverflow.com/questions/12731460/multiple-uialertviews-in-the-same-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!