UIActionSheet with Block

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.

猜你喜欢

转载自zl4393753.iteye.com/blog/1727387