Saturday, September 14, 2013

UIAlertView with Blocks

For the Programmers...

I'm not sure why Apple didn't do this one when adding blocks to everything.  A bit of code to do an UIAlertView with passing in a block to handle the button tapped. (It also uses a NSArray rather than a null-terminated list.)

I've not done it yet, but would be simple to do a similar thing with UIActionSheet too.


////////////////////////////////////////////////////////////////
//.H file...
//Helper to store the block

@interface UIAlertViewBlock : UIAlertView
@property (nonatomic, copy)  void (^clickBlock)(NSInteger buttonIndex);
@end


@interface UIAlertView (MichaelBurfordBlocks)
+ (void)alertWithTitle:(NSString *)title
               message:(NSString *)message
     cancelButtonTitle:(NSString *)cancelButtonTitle
     otherButtonTitles:(NSArray *)otherButtonTitles
         clickedButton:(void (^)(NSInteger buttonIndex))block;
@end

////////////////////////////////////////////////////////////////
//.M file...
@implementation UIAlertViewBlock
- (void)alertView:(UIAlertView *)alertView 
             clickedButtonAtIndex:(NSInteger)buttonIndex {
 self.clickBlock(buttonIndex);
}

- (void)dealloc {
 self.clickBlock = nil;
 [super dealloc];
}
@end


@implementation UIAlertView (MichaelBurfordBlocks)

+ (void)alertWithTitle:(NSString *)title
               message:(NSString *)message
     cancelButtonTitle:(NSString *)cancelButtonTitle
     otherButtonTitles:(NSArray *)otherButtonTitles
         clickedButton:(void (^)(NSInteger buttonIndex))block {
 UIAlertViewBlock *alert = [[UIAlertViewBlock alloc] 
                                       initWithTitle:title
                                             message:message
                                            delegate:nil
                                   cancelButtonTitle:cancelButtonTitle
                                   otherButtonTitles:nil];
        alert.clickBlock = block;
 alert.delegate = alert;
 for (NSString* otherTitle in otherButtonTitles) {
  [alert addButtonWithTitle:otherTitle];
 }
 [alert show];
        [alert autorelease];
}


///////////////////////////////////////////////////////////////
//Then you get to use it like this!
[UIAlertView alertWithTitle:NSLocalizedString(@"Buy My App", nil) 
                    message:NSLocalizedString(@"Please Buy My App", nil)
          cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
          otherButtonTitles:@[NSLocalizedString(@"Buy Now", nil)]
              clickedButton:^(NSInteger buttonIndex) {
                  if (buttonIndex==1) {
                      if ([SKPaymentQueue canMakePayments] && buyItem) {
                          SKPayment *payment = [SKPayment paymentWithProduct:buyItem];
                          [[SKPaymentQueue defaultQueue] addPayment:payment];
                      }
                  }
              }];


No comments: