Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a function for UIAlertView?

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

like image 621
zardon Avatar asked Jun 10 '10 07:06

zardon


2 Answers

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.

like image 51
zoul Avatar answered Sep 23 '22 23:09

zoul


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.

like image 36
Frank Shearar Avatar answered Sep 22 '22 23:09

Frank Shearar