现在的位置: 首页 > 综合 > 正文

自封装UIAlert类:BlockAlertView

2018年01月28日 ⁄ 综合 ⁄ 共 1543字 ⁄ 字号 评论关闭

.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];

抱歉!评论已关闭.