UIActionSheet with Block

常彭薄
2023-12-01
If you've done any iPhone development, you'll know that using UIActionSheet is a bit complicated -- more so if you want to share an action sheet implementation across view controllers, or display multiple UIActionSheets from a single view controller.

If you've used UIActionSheet in the past, you've had to do the following:

Create a UIActionSheet instance in your view controller.
Add the UIActionSheetDelegate protocol to your view controller.
Add the -[UIActionSheetDelegate actionSheet:clickedButtonAtIndex:] delegate method.
Match the button index and source action sheet to your intended action, fetch any state you need, and execute.
Using blocks, we can significant reduce the effort required to define and use a UIActionSheet. Instead of defining a delegate, and matching index values to your button actions, we can simply pass a block that implements the button's action directly:


- (void) displaySheet {
PLActionSheet *sheet = [[PLActionSheet alloc] initWithTitle: @"Destination"];

/* A re-usable block that simply displays an alert message */
void (^alert)(NSString *) = ^(NSString *message) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Destination Selected"
message: message
delegate: nil
cancelButtonTitle: @"OK"
otherButtonTitles: nil];

[alert show];
[alert release];
};

[sheet addButtonWithTitle: @"Work" block: ^{
alert(@"Work selected");
}];

[sheet addButtonWithTitle: @"Home" block: ^{
alert(@"Home selected");
}];

[sheet addButtonWithTitle: @"School" block: ^{
alert(@"School selected");
}];

[sheet setCancelButtonWithTitle: @"Cancel" block: ^{}];

[sheet showInView: self.window];
[sheet release];
}


That's it -- there is nothing else. The blocks used for each button automatically have access to the enclosing method's variables, and we even use another block (alert) to avoid retyping the UIAlertView boilerplate or cluttering our class with an alert method.
 类似资料:

相关阅读

相关文章

相关问答