我有两个带有ok/cancel按钮的UIAlertViews。
我通过以下方式捕获用户的响应:

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

我的问题是,哪个alertView当前处于打开状态?
在每个按钮上单击“确定/取消”时,我需要执行不同的操作...

最佳答案

您有几种选择:

  • 使用ivars。创建警报 View 时:
    myFirstAlertView = [[UIAlertView alloc] initWith...];
    [myFirstAlertView show];
    // similarly for the other alert view(s).
    

    并在委托(delegate)方法中:
    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        if (alertView == myFirstAlertView) {
            // do something.
        } else if (alertView == mySecondAlertView) {
            // do something else.
        }
    }
    
  • 使用tagUIView属性:
    #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;
        }
    }
    
  • 子类UIAlertView并添加userInfo属性。这样,您可以向警报 View 添加标识符。
    @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.
        }
    }
    
  • 关于objective-c - 同一 View 中有多个UIAlertViews,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12731460/

    10-10 06:59