Make UIAlertView blocking

后端 未结 5 2051
刺人心
刺人心 2020-12-03 12:49

I need make UIAlertView blocking. Because i have function and i need to return UIAlertView choice. But problem is that after UIAlertView

5条回答
  •  臣服心动
    2020-12-03 13:12

    This doesn't make it blocking, but I have written a subclass to add block style syntax which makes it much easier to handle the buttonClickedAtIndex method without having to do a delegate and a whole bunch of if statements if you have multiple UIAlertViews in one class.

    #import 
    
    @interface UIAlertViewBlock : UIAlertView
    - (id) initWithTitle:(NSString *)title message:(NSString *)message block: (void (^)(NSInteger buttonIndex))block
       cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_AVAILABLE(10_6, 4_0);
    @end
    
    
    #import "UIAlertViewBlock.h"
    
    @interface UIAlertViewBlock()
    {
        void (^_block)(NSInteger);
    }
    @end
    
    @implementation UIAlertViewBlock
    
    - (id) initWithTitle:(NSString *)title message:(NSString *)message block: (void (^)(NSInteger buttonIndex))block
    cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_AVAILABLE(10_6, 4_0)
    {
        if (self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil])
        {
            _block = block;
        }
        return self;
    }
    
    - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        _block(buttonIndex);
    }
    
    @end
    

    Then to call it here is some example code. The other cool part is that because a block closes around the local variables, I can have access to all the state that existed at the time I show the UIAlertView. Using the traditional delegate approach, you would have to store all that temporary state into class level variables to have access to it in the call to buttonClickedAtIndex in the delegate. This is so much cleaner.

    {
        NSString *value = @"some random value";
        UIAlertViewBlock *b = [[UIAlertViewBlock alloc] initWithTitle:@"Title" message:@"Message" block:^(NSInteger buttonIndex)
            {
                if (buttonIndex == 0)
                    NSLog(@"%@", [value stringByAppendingString: @" Cancel pressed"]);
                else if (buttonIndex == 1)
                    NSLog(@"Other pressed");
                else
                    NSLog(@"Something else pressed");
            }
            cancelButtonTitle:@"Cancel" otherButtonTitles:@"Other", nil];
    
        [b show];
    }
    

提交回复
热议问题