2

我有一个我们要求用户输入的密码 UIAlertView。我需要根据场景在不同的视图上询问它,从 downloadViewController(在用户下载他们的数据之后),当他们切换到他们的数据(如果用户有多个帐户,每个帐户都有一个密码),以及当应用从睡眠中醒来(来自应用程序委托)。

我有常见的 UIAlertView 代码,基本上检查数据库的密码和内容。有没有放置这个通用代码的好地方?我觉得我正在复制并粘贴警报的显示和此警报的委托方法。在某些视图控制器中,也会有其他警报,我必须通过该特定 ViewController 中的 UIAlertViewDelegate 来响应这些警报。

4

1 回答 1

1

您可以像这样创建一个类别,然后重用代码:

*.h 文件

@interface UIViewController(Transitions)

- (void) showAlertWithDelegate: (id) delegate;

@end

*.m 文件

-(void) showAlertWithDelegate:(id)delegate {

    id _delegate = ( delegate == nil) ? self : delegate;
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle: NSLocalizedString(@"Alert Text",@"Alert Text")
                          message: NSLocalizedString( @"Msg Alert",@"Msg Alert")
                          delegate:_delegate 
                          cancelButtonTitle:nil
                          otherButtonTitles: NSLocalizedString(@"OK",@"OK"),nil];
    [alert setTag:0]; //so we know in the callback of the alert where we come from - in case we have multiple different alerts
    [alert show];
}

//the local callback for the alert - this handles the case when we call the alert with delegate nil
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    D_DBG(@"%i %i",[alertView tag],buttonIndex);
}

在需要警报的 UIViewController 类中导入 *.h 文件。

现在,如果您这样调用:

   [self showAlertWithDelegate:nil];

它将显示您的警报,并且代表将被实施

 - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex

当你这样称呼它时,在界面中:

   [self showAlertWithDelegate:self];

您需要提供回调

 - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex

在您调用它的类中,因此您可以处理用户按下的任何内容 - 与界面中实现的内容不同。

于 2012-09-24T21:24:33.187 回答