Writing a function for UIAlertView?

I'm tired of writing basic UIAlertView, i.e.

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

Instead, you can include all of this in a โ€œhelperโ€ function, where can I return buttonIndex or something like a warning, which usually returns?

For a simple helper function, I think you could combine the parameters for the header, the message, I'm not sure if you can pass delegates to the parameter, though, or lay out the information.

In pseudocode, it could be like this:

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

Any help on this would be great.

thanks

+6
objective-c iphone uialertview
source share
2 answers

This is what I wrote when I felt bad the same thing:

 -(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 cannot write a function that will display a warning and then return a value, for example, buttonIndex, because this return value only occurs when the user clicks the button and your delegate does something.

In other words, the query process using UIAlertView is asynchronous.

+2
source share

In 4.0+, you can simplify the warning code using blocks, something 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 Warning on GitHub .

+14
source share

All Articles