實作對UIAlertController和UIAlertView判斷系統後的簡單封裝
iOS8之後用UIAlertController代替了UIAlertView,是以每次有需要彈窗的時候,都需要先判斷系統,最近在做的項目中彈窗較多,如果每次都判斷,真是太麻煩了,索性對UIAlertController和UIAlertView進行的封裝了,封裝在一個工具類中,在工具類中就對系統進行判斷,然後在你需要彈窗的界面直接調用這個工具類的方法就可以了,減少了代碼的耦合.
這個工具類其實也封裝的特别簡單,因為都是用的系統的,分享出來給大家參考下:
首先是.h檔案
[objc] view plaincopy
- @interface UIAlertTool : NSObject
- -(void)showAlertView:(UIViewController *)viewController :(NSString *)title :(NSString *)message :(NSString *)cancelButtonTitle :(NSString *)otherButtonTitle :(void (^)())confirm :(void (^)())cancle;
- @end
隻有這麼一個簡單的方法 把你需要在彈窗中顯示的内容以參數的形式傳入就可以了
然後是.m檔案的實作
[objc] view plaincopy
- #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==) {
- confirmParam();
- }
- else{
- cancleParam();
- }
- }
- @end