如何检查UIAlertView的返回值?

时间:2013-03-12 09:20:16

标签: objective-c cocoa-touch

我想检查用户是否点击“是”,例如我想要采取某种行动。

这是我的代码行:

UIAlertView* mes=[[UIAlertView alloc] initWithTitle:@"Are you sure?" message:@"this will start a new game" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];

    [mes show];

所以我想说if user tap "yes" preform this action

这是我的方法:我想说如果用户点击“是”创建新游戏。

- (IBAction)newGame:(UIButton *)sender {

    UIAlertView* mes=[[UIAlertView alloc] initWithTitle:@"Are you sure?" message:@"this will start a new game" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];

    [mes show];


    self.flipsCount = 0;
    self.game = nil;
    for (UIButton *button in self.cardButtons) {
        Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]];
        card.unplayble = NO;
        card.faceUp = NO;
        button.alpha = 1;
    }

    self.notificationLabel.text = nil;
    [self updateUI];
}

3 个答案:

答案 0 :(得分:1)

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
     if (buttonIndex != [alertView cancelButtonIndex])
    {
        //User clicked ok
        NSLog(@"ok");
       [self newGame:[UIButton alloc] ];
    }
    else
    {
        //User clicked cancel
        NSLog(@"cancel");
    }
}

它从左到右采用ButtonIndex值。

答案 1 :(得分:0)

使用UIAlertView的委托方法

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   if (buttonIndex == 1)//Yes
   {
       self.flipsCount = 0;
       self.game = nil;
       for (UIButton *button in self.cardButtons) 
       {
            Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]];
            card.unplayble = NO;
            card.faceUp = NO;
            button.alpha = 1;
       }

       self.notificationLabel.text = nil;
       [self updateUI];
   }
   else//No 
   {
       //do something
   }
}

答案 2 :(得分:0)

在同一个类(或您设置为delegate的类中)插入以下方法:

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
  if (buttonIndex == 0)
  {
    //User clicked ok
  }
  else
  {
    //User clicked cancel
  }
}