5

我正在尝试在单个视图控制器中执行具有两个警报的微笑任务。下面的代码工作正常,但我将如何在视图控制器的其他地方创建另一个实例。我担心如果我复制代码,我的 buttonIndex 将不知道它正在响应哪个警报。有任何想法吗?谢谢!

-(void)alertChoice
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
    message:@"Message" delegate:self
    cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) 
    {
    //do something
    }
}
4

4 回答 4

25

您可以使用tagon 属性UIAlertView来破译哪个警报是哪个:

-(void)alertChoice
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
    message:@"Message" delegate:self
    cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
    alert.tag = 0;
    [alert show];
}

-(void)alertChoice1
{
    UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Title"
    message:@"Message" delegate:self
    cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
    alert1.tag = 1;
    [alert1 show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 0)
    {
    }
}
于 2013-01-31T09:04:42.470 回答
2

将标签设置为警报视图。

alert.tag = 1;

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && alertView.tag == 1) 
    {
    //do something
    }
}
于 2013-01-31T09:04:44.737 回答
2

只需为每个警报视图设置一个标签,然后检查哪个发送了消息。

alertView.tag=0;

进而

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

if(alertView.tag==0){

      if(buttonIndex == 0)//OK button pressed
     {
       //do something
     }
     else if(buttonIndex == 1)//Annul button pressed.
     {
      //do something
     }
}else{

  if(buttonIndex == 0)//OK button pressed

       {
        //do something
      }
      else if(buttonIndex == 1)//Annul button pressed.
    {
    //do something
    }
  }
于 2013-01-31T09:06:46.227 回答
1

第 1 步:在视图 controller.h 文件中添加UIAlertViewDelegate

第 2 步:在 view controller.m 文件中添加以下方法

-(void)AlertMethodOne
{
  UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"AlertMethodOne" message:@"AlertMethodOne successfully Called" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
    alert.tag=101;
    [alertview show];  
}

-(void)AletrMethodTwo
{
UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"AletrMethodTwo" message:@"AlertMethodTwo successfully Called" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
alert.tag=102;
    [alertview show]; 
}

在 viewController 中调用上述两个方法,如下所示: [self AlertMethodOne]; [自我警报方法二];

现在 AlertView 按钮单击方法

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag==101)
{
   if (buttonIndex == 0)
   {
   }
}
if(alertView.tag==102)
{
   if (buttonIndex == 1)
   {  
   }
}
}
于 2013-03-30T10:09:27.867 回答