6

我厌倦了编写基本的 UIAlertView,即:

UIAlertView *alert = [[UIAlertView alloc] initWith...]] //etc

除了这样做之外,是否可以将所有这些放在“帮助”函数中,在那里我可以返回 buttonIndex 或警报通常返回的任何内容?

对于一个简单的辅助函数,我想您可以为标题、消息提供参数,但我不确定您是否可以在参数中传递委托或捆绑信息。

在伪代码中,它可能是这样的:

someValueOrObject = Print_Alert(Title="", Message="", Delegate="", Bundle="") // etc

对此的任何帮助都会很棒。

谢谢

4

2 回答 2

14

在 4.0+ 中,您可以使用块简化警报代码,有点像这样:

CCAlertView *alert = [[CCAlertView alloc]
    initWithTitle:@"Test Alert"
    message:@"See if the thing works."];
[alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"Foo"); }];
[alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"Bar"); }];
[alert addButtonWithTitle:@"Cancel" block:NULL];
[alert show];

请参阅GitHub 上的 Lambda 警报

于 2010-06-15T10:02:13.343 回答
2

这是我写的,当我厌倦了做同样的事情时:

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName {
  [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: nil];
}

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName informing:(id)delegate {
  [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: delegate];
}

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName withExtraButtons:(NSArray *)otherButtonTitles informing:(id)delegate {
  UIAlertView *alert = [[UIAlertView alloc]
              initWithTitle: title
              message: message
              delegate: delegate
              cancelButtonTitle: firstButtonName
              otherButtonTitles: nil];
  if (otherButtonTitles != nil) {  
    for (int i = 0; i < [otherButtonTitles count]; i++) {
      [alert addButtonWithTitle: (NSString *)[otherButtonTitles objectAtIndex: i]];
    }
  }
  [alert show];
  [alert release];
}

但是,您不能编写一个显示警报然后返回像 buttonIndex 这样的值的函数,因为该值返回仅在用户按下按钮并且您的委托执行某些操作时发生。

换句话说,用 提出问题的过程UIAlertView是异步的。

于 2010-06-10T07:25:34.680 回答