Alex Rivera | Logout

Block for UIAlertViewDelegate

Asked 2012-04-10T02:26:11.317
25

I'm pretty new to objective C and I'm just trying to figure out if I can use a block or a selector as the UIAlertViewDelegate argument for UIAlertView - and which is more appropriate?

I've tried the following but it just isn't working so I'm not sure if I'm on the right track or not?

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Checked In" 
    message:responseString
    delegate:^(UIAlertView * alertView, NSInteger buttonIndex)
                                                    {
                                                       NSLog(@"Done!");
                                                   } 
    cancelButtonTitle:@"OK" 
    otherButtonTitles: nil];

Thanks!

Edit
Report

2 Answers

1

This is an update to danh's implementation, which is incomplete because it is not possible to add multiple buttons. Passing a va_list to a function is a little tricky :-)

So you could do this, in order to be able to add multiple buttons to the UIAlertView:

- (id)initWithTitle:(NSString *)title message:(NSString *)message completion:(void (^)(NSInteger buttonIndex))completion cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... {

    self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil ];


    if(self){
        _completion = completion;

        va_list _arguments;
        va_start(_arguments, otherButtonTitles);

        for (NSString *key = otherButtonTitles; key != nil; key = (__bridge NSString *)va_arg(_arguments, void *)) {
                [self addButtonWithTitle:key];
        }
        va_end(_arguments);

    }

    return self;
}

Update: There might be a better way of passing the va_list to super. I would like to mention that to me va_lists have something mystic to them :-)

answered 2012-08-25T16:42:19.550
-2

I had to edit the calling example a bit to stop complier error. Just a small tweak and xcode was happy.

UIAlertViewBlock *alert = [[UIAlertViewBlock alloc] initWithTitle:@"hi"
                                                          message:@"hi there"
                                                       completion:^(BOOL canceled,NSInteger buttonIndex) {
                                                           NSLog(@"canceled=%d", canceled);
                                                           NSLog(@"pressed=%d", buttonIndex);
                                                       }
                                               cancelButtonTitle:@"cancel"
                                                otherButtonTitles:@"ok", nil];
[alert show];
answered 2012-10-31T02:41:31.603

Your Answer