實現對UIAlertController和UIAlertView判斷系統後的簡單封裝

iOS8之後用UIAlertController代替了UIAlertView,所以每次有需要彈窗的時候,都需要先判斷系統,最近在做的項目中彈窗較多,如果每次都判斷,真是太麻煩了,索性對UIAlertController和UIAlertView進行的封裝了,封裝在一個工具類中,在工具類中就對系統進行判斷,然後在你需要彈窗的界面直接調用這個工具類的方法就可以了,減少了代碼的耦合.

這個工具類其實也封裝的特別簡單,因爲都是用的系統的,分享出來給大家參考下:

首先是.h文件

@interface UIAlertTool : NSObject
-(void)showAlertView:(UIViewController *)viewController :(NSString *)title :(NSString *)message :(NSString *)cancelButtonTitle :(NSString *)otherButtonTitle :(void (^)())confirm :(void (^)())cancle;;
@end

只有這麼一個簡單的方法  把你需要在彈窗中顯示的內容以參數的形式傳入就可以了

然後是.m文件的實現

#define IAIOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#import "UIAlertTool.h"
typedef void (^confirm)();
typedef void (^cancle)();
@interface UIAlertTool(){
  confirm confirmParam;
  cancle  cancleParam;
}
@end
@implementation UIAlertTool
-(void)showAlertView:(UIViewController *)viewController :(NSString *)title :(NSString *)message :(NSString *)cancelButtonTitle :(NSString *)otherButtonTitle :(void (^)())confirm :(void (^)())cancle{
  confirmParam=confirm;
  cancleParam=cancle;
  if (IAIOS8) {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
       cancle();
    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
      confirm();
    }];
    // Add the actions.
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    [viewController presentViewController:alertController animated:YES completion:nil];
  }
  else{
    UIAlertView *TitleAlert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:otherButtonTitle otherButtonTitles:cancelButtonTitle,nil];
    [TitleAlert show];
  }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  if (buttonIndex==0) {
    confirmParam();
  }
  else{
    cancleParam();
  }
}
@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章