编写一个用于UIAlertView的函数?

6

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

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

有没有可能将所有这些放在“助手”函数中,从而可以返回buttonIndex或任何警报通常返回的内容?

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

伪代码如下:

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

任何关于这个的帮助都将是非常棒的。
谢谢。

这个标签可能需要更好的标记。考虑添加 objective-c, iphone 等标签。 - David Foster
2个回答

14

在4.0版本以上你可以使用块(block)来简化警告(alert)代码,像这样:

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 Alert


非常流畅的解决方案。对我来说非常有效。 - Kongress
有没有不使用 LambdaAlert 类的方法来实现这个? - Chris
你的意思是使用原始的 UIAlertView 类吗?不是的。你需要编写一些支持代码,这正是 LambdaAlert 所做的。为什么要避免它呢? - zoul

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提出问题的过程是异步的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接