繁体   English   中英

有多个警报视图时按下检测按钮

[英]Detecting button pressed when there are multiple alert views

我在一个视图中有多个警报视图,我使用此代码来检测按下了哪个按钮:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  

    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];  

    if ([title isEqualToString:@"OK"]) {

          //for one alert view
          [passCode becomeFirstResponder];

     } else if ([title isEqualToString:@" OK "]) {

        //for another alert view, had to change "OK" to " OK "
        [passCodeConfirm becomeFirstResponder];

    }
}   

现在,由于在一个视图中有多个警报视图可以执行不同的操作,因此我必须诱使用户认为“OK”和“OK”是相同的。 它工作和看起来很好,但它感觉有点混乱。 当然还有另一种方法可以做到这一点,例如将其特定于警报视图,然后使其特定于另一个。 你知道我会怎么做吗? 谢谢!

为单独的UIAlertView设置唯一标记并在其委托方法中识别和访问将更具技术性和更好性。

例如,

    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Message" message:@"Are You Sure you want to Update?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok",nil];
    [alert setTag:1];
    [alert show];
    [alert release];

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
    {
        if(alertView.tag == 1)
        {
            // set your logic
        }
    }

使用tag属性唯一标识您创建的每个alertview。

像这样

myAlertView.tag = 1

然后在clickedButtonAtIndex委托方法中检查使用此标记属性单击了哪个alertview的按钮,

if(alertView.tag==1)

我不会使用标题来区分按钮。 当您的应用程序已本地化或您决定更改按钮标题时,您会遇到问题,但忘记在任何地方更新它们。 使用按钮索引,或者如果除了取消按钮之外只有一个按钮,请使用UIAlertViewcancelButtonIndex属性。

要区分多个警报视图,可以使用其tag属性。

在您的视图中,为每个警报视图添加属性。

UIAlertView *myAlertType1;
UIAlertView *myAlertType2;

@property (nonatomic, retain) UIAlertView *myAlertType1;
@property (nonatomic, retain) UIAlertView *myAlertType2;

使用这些属性创建警报

self.myAlertType1 = [[[UIAlertView alloc] initWithTitle: ... etc] autorelease];
[self.myAlertType1 show];

然后在你的委托方法中:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView == myAlertType1) {
         // check the button types and add behaviour for this type of alert
    } else if (alertView == myAlertType2 {
         // check the button types and add behaviour for the second type of alert
    }
}

编辑:虽然上述工作,但iApple建议使用标签似乎更清晰/更简单。

 //in your .h file
  UIAlertView* alert1;
  UIAlertView* alert2;

  //in your .m file
  // when you are showing your alerts, use
  [alert1 show]; //or
  [alert2 show];

  //and just check your alertview in the below method

  - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
  {  
       if(alertView == alert1)
       {
              //check its buttons
       }
       else   //check other alert's btns
  }   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM