.h文件
typedef void (^blockAlertViewCallBackBlock)(int btnIndex); #import <Foundation/Foundation.h> @interface BlockAlertView : NSObject - (void)showAlertWithTitle:(NSString *)title msg:(NSString *)msg callbackBlock:(blockAlertViewCallBackBlock)block cancelButtonTitle:(NSString *)cancelBtnTitle otherButtonTitles:(NSString *)otherButtonTitles, ... ; @end
.m文件
#import "BlockAlertView.h" @implementation BlockAlertView { blockAlertViewCallBackBlock _callbackBlock; } - (void)dealloc { [_callbackBlock release]; _callbackBlock = nil; [super dealloc]; } - (void)showAlertWithTitle:(NSString *)title msg:(NSString *)msg callbackBlock:(blockAlertViewCallBackBlock)block cancelButtonTitle:(NSString *)cancelBtnTitle otherButtonTitles:(NSString *)otherButtonTitles, ... ; { if (!block) { return; } _callbackBlock = nil; //强引用 _callbackBlock = [block copy]; [self retain]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancelBtnTitle otherButtonTitles:nil]; if (otherButtonTitles) { [alert addButtonWithTitle:otherButtonTitles]; va_list args ; va_start(args, otherButtonTitles); NSString *title = nil; while ((title = va_arg(args, NSString *))) { [alert addButtonWithTitle:title]; } va_end(args); } [alert show]; [alert release]; alert = nil; } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex; { _callbackBlock(buttonIndex); [self release]; } @end
BlockAlertView类的使用方法:
BlockAlertView *blockAlert = [BlockAlertView new]; [blockAlert showAlertWithTitle:@"标题" msg:@"内容" callbackBlock:^(int btnIndex){ if (btnIndex == 0) { return ; } } cancelButtonTitle:@"确定" otherButtonTitles: nil]; [blockAlert release];