【问题标题】:iOS alertview action on a button按钮上的 iOS alertview 操作
【发布时间】:2013-02-02 17:50:01
【问题描述】:

我在菜单中有一个按钮,当触摸它时,会弹出一条带有两个按钮的警报消息:“Cancel”和“Yes”。这是我的警报代码:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game"
                                                message:@"Are you sure?"
                                               delegate:nil
                                      cancelButtonTitle:@"Cancel"
                                      otherButtonTitles:@"Yes", nil];
[alert show];

是否可以为按钮“Yes”添加动作?

【问题讨论】:

    标签: ios xcode alertview


    【解决方案1】:

    在您的代码中设置 UIAlertView 委托:

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil]; [alert show];
    

    因为你已经将委托设置为self,所以在同一个类中编写委托函数,如下所示:

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) { // Set buttonIndex == 0 to handel "Ok"/"Yes" button response
        // Cancel button response
        }}
    

    【讨论】:

      【解决方案2】:

      你需要实现UIAlertViewDelegate

      并添加以下内容...

      - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
          if (buttonIndex == 1) {
              // do stuff
          }
      }
      

      【讨论】:

      • 如果你有多个UIAlertViews,你应该设置标签来描述哪个被调用。
      【解决方案3】:

      是的,这很容易。看到您现在设置为 nil 的名为“delegate”的参数了吗?将其设置为一个对象...如果您从视图控制器调用它,通常是“self”,然后为 UIAlertViewDelegate 实现选择器。

      您还需要声明您的视图控制器符合 UIAlertViewDelegate 协议。这样做的好地方是在视图控制器的“私有”延续类中。

      @interface MyViewController() <UIAlertViewDelegate>
      @end
      
      - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
      {
         NSLog(@"Button pushed: %d", buttonIndex);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 2012-04-13
        • 1970-01-01
        相关资源
        最近更新 更多