开发者

Writing a function for UIAlertView?

开发者 https://www.devze.com 2023-01-03 11:40 出处:网络
I\'m sick of writing basic UIAlertView\'s, ie: UIAlertView *alert = [[UIAlertView alloc] initWith...]] //etc

I'm sick of writing basic UIAlertView's, ie:

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

Instead of doing this, is it possible to put all this in a "helper" function, where I can return the buttonIndex, or whatever an alert usually returns?

For a simple helper 开发者_StackOverflow社区function I guess you could feed parameters for the title, message, I'm not sure whether you can pass delegates in a parameter though, or bundle info.

In pseudo-code, it could be like this:

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

Any help on this would be great.

Thanks


In 4.0+ you can simplify the alert code using blocks, a bit like this:

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];

See Lambda Alert on GitHub.


This is what I wrote, when I got sick of doing the same:

-(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];
}

You can't write a function that will display an alert and then return a value like a buttonIndex though, because that value-returning only occurs when the user presses a button and your delegate does something.

In other words, the process of asking a question with the UIAlertView is an asynchronous one.

0

精彩评论

暂无评论...
验证码 换一张
取 消