菜鸟学IOS编程—不同系统版本下Alert整合

来源:互联网 发布:淘宝丝芙兰 编辑:程序博客网 时间:2024/06/06 16:52

菜鸟编程,不喜勿喷~

在写项目时alert使用率比较高,出现了2个问题:

1.满屏的alert适配ios版本代码,太乱不易于维护

2.ios7的alert没有block,用的不是很随意

为解决以上两个问题,总结出以下代码供参考:

使用方法:

[Alert createAlert:@"标题" alertMsg:@"内容" alertBtnNames:@[@"确定"] result:^(NSInteger btnIndex) {          NSLog(@"%ld", (long)response);        }];

解决ios不同系统版本的问题:

Alert.h

/** *  Alert * *  @param title    alert标题 *  @param message  alert内容 *  @param namesArr alert按钮名称 *  @param result   返回点击按钮index */+ (void)createAlert:(NSString*)title alertMsg:(NSString*)message alertBtnNames:(NSArray*)namesArr result:(void(^)(NSInteger response))result;

Alert.m

+ (void)createAlert:(NSString*)title alertMsg:(NSString*)message alertBtnNames:(NSArray*)namesArr result:(void(^)(NSInteger btnIndex))result{  if(IS_IOS8)  {    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];    for (NSInteger i = 0; i<[namesArr count]; i++) {        [alert addAction:[UIAlertAction actionWithTitle:[namesArr objectAtIndex:i] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {            result(i);        }]];    }    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:^{}];  }  else  {    BlockUIAlertView *blockAlert = [[BlockUIAlertView alloc] initWithTitle:title message:message buttonTitles:namesArr clickButton:^(NSInteger i) {      result(i);    }];    [blockAlert show];  }}

解决ios7没有block的问题:

BlockUIAlertView.h

typedef void(^AlertBlock)(NSInteger);@interface BlockUIAlertView : UIAlertView@property(nonatomic,copy)AlertBlock block;- (id)initWithTitle:(NSString *)title            message:(NSString *)message  buttonTitles:(NSArray *)buttonTitles        clickButton:(AlertBlock)_block;
BlockUIAlertView.m

@synthesize block;- (id)initWithTitle:(NSString *)title            message:(NSString *)message       buttonTitles:(NSArray *)buttonTitles        clickButton:(AlertBlock)_block{  self = [super initWithTitle:title message:message delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];  for(NSString *str in buttonTitles){    [self addButtonWithTitle:str];  }  self.cancelButtonIndex = [buttonTitles count] - 1;  if (self) {    self.block = _block;  }  return self;}- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{  self.block(buttonIndex);}




0 0