2011-08-19 66 views
27

我在一个视图中的多个警报意见,我用这个代码来检测哪个按钮被按下:检测按钮按下时有多个警报意见

-(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”是一回事。它工作,看起来很好,但它感觉有点混乱。当然还有另外一种方法可以做到这一点,比如将这个特定于一个警报视图,然后将其具体化为另一个视图。你知道我会怎么做吗?谢谢!

回答

55

对于单独的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 
     } 
    } 
+0

我喜欢这个比我更好的解决方案上面 – gamozzii

+0

很好,谢谢您帮帮我!标签可以分配给几乎任何UI对象吗? –

+0

所有支持标记的getter/setter属性的UI对象,开发人员都可以指定。只要同一类别必须有唯一标签才能正确回应。 –

2

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

要区分多个警报视图,您可以使用它们的tag属性。

2

在您看来,每个警报视图中添加属性。

编辑:虽然上面的作品,使用标签的iApple的建议似乎更清洁/简单

UIAlertView *myAlertType1; 
UIAlertView *myAlertType2; 

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

使用这些属性

self.myAlertType1 = [[[UIAlertView alloc] initWithTitle: ... etc] autorelease]; 
[self.myAlertType1 show]; 
在你的委托方法

然后创建警报。

+2

我不喜欢使用标签,因为当对象应该告诉你你需要知道什么时,你必须添加和访问额外的信息。 –

1
//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 
    } 
4

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

喜欢这个

myAlertView.tag = 1 

然后使用这个标签属性点击了哪个alertview的按钮clickedButtonAtIndex委托方法检查,

if(alertView.tag==1)