程序员

便捷的使用系统AlertController弹框

2018-10-19  本文已影响39人  MR_詹

阅读此篇文章前建议阅读前篇Block的多种使用场景

在封装AlertController前,先复习一下AlertController的用法,showTime

UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"标题" message:@"提示语" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"默认风格" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];
[alertC addAction:action1];
[alertC addAction:action2];
[self presentViewController:alertC animated:YES completion:nil];

虽然系统的调用方法也是很简洁,如果只使用一次的话,那没关系,但是如果多个地方要使用的时候,你就会发现代码量不少、步骤也重复,所以不方便

image.png

第一次尝试使用思维导图整理逻辑(比较丑,我们就将就点),如上图所示,我们以“分-总”的方式分析
要封装的控件:
AlertController和AlertAction
输入的内容:
有两种,一种是只有一次(A),另一种是自由配置(B)。对于"A"的情况,考虑的就是在API处直接添加入参则可以,而对于B则使用建模的方式配置,如AlertActionModel(基本属性:title、style)
响应:
这也是相同的道理,在封装功能的时候对一些可配置和一些只调用一次额做分类,这样更能清楚在API处要暴露什么入参或回调。对此,“展示present”的跳转则不会暴露,而AlertAction的点击响应则需要公开出来

根据上面的分析,API总体的构成要素基本是定下来的,如下


image.png

而功能的调用方式,本人是考虑使用ViewController的分类,也符合MVC和MVVM主流设计模式中ViewController的功能职责,不会有冲突

开始撸代码...(代码都带有注释,就不解释了)

//UIViewController+LZAlertViewController.m文件

#import <UIKit/UIKit.h>

@class LZAlertController;

#pragma mark - I LZAlertController构造
/**
 alertAction配置链

 @param title 标题
 @return LZAlertController对象
 */
typedef LZAlertController *_Nonnull (^LZAlertActionTitle)(NSString * _Nonnull title);

/**
 alertz按钮执行回调

 @param buttonIndex 按钮index
 @param action UIAlertAction对象
 @param alertSelf 本类对象
 */
typedef void (^LZAlertActionBlock)(NSInteger buttonIndex, UIAlertAction * _Nonnull action, LZAlertController * _Nonnull alertSelf);

@interface LZAlertController : UIAlertController
/* alert弹出后,可配置的回调 **/
@property (nullable, nonatomic, copy) void (^alertDidShown)(void);
/* alert关闭后, 可配置的回调 **/
@property (nullable, nonatomic, copy) void (^alertDidDismiss)(void);
/* 设置toast模式展示时间:如果alert未添加任何按钮,将会以toast样式展示,默认一秒 **/
@property(nonatomic,assign ) NSTimeInterval  toastStyleDuration;

/**
 禁用alert弹出动画,默认执行系统的默认弹出动画
 */
- (void)alertAnimateDisabled;

/**
 链式构造alert视图按钮,添加一个alertAction按钮,默认样式,参数为标题

 @return LZAlertController 对象
 */
- (LZAlertActionTitle _Nonnull )addActionDefaultTitle;

/**
 链式构造alert视图按钮,添加一个alertAction按钮,取消样式,参数为标题

 @return LZAlertController 对象
 */
- (LZAlertActionTitle _Nonnull )addActionCancleTitle;

/**
 链式构造alert视图按钮,添加一个alertAction按钮,警告样式,参数为标题

 @return LZAlertController 对象
 */
- (LZAlertActionTitle _Nonnull )addActionDestructiveTitle;

@end



#pragma mark - II 类别
/* alert构造块 **/
typedef void (^LZAlertAppearanceProcess)(LZAlertController * _Nonnull alertMaker);

@interface UIViewController (LZAlertViewController)

/**
 show-alert(iOS_8.0)

 @param title title
 @param message message
 @param appearanceProcesss alert配置过程
 @param actionBlock alert点击响应回调
 */
- (void)lz_showAlertWithTitle:(nullable NSString *)title
                      message:(nullable NSString *)message
            appearanceProcess:(LZAlertAppearanceProcess _Nonnull )appearanceProcesss
                 actionsBlock:(nullable LZAlertActionBlock)actionBlock;

/**
 show-actionSheet(iOS_8.0)

 @param title title
 @param message message
 @param appearanceProcess actionSheet配置过程
 @param actionBlock actionSheet点击响应回调
 */
- (void)lz_showActionSheetWithTitle:(nullable NSString *)title
                            message:(nullable NSString *)message
                  appearanceProcess:(LZAlertAppearanceProcess _Nonnull )appearanceProcess
                       actionsBlock:(nullable LZAlertActionBlock)actionBlock;

@end
//UIViewController+LZAlertViewController.m文件

#import "UIViewController+LZAlertViewController.h"

/* 默认展示时间 **/
static NSTimeInterval const LZAlertShowDurationDefault = 1.0f;

#pragma mark - I AlertActionModel
@interface LZAlertActionModel : NSObject
@property(nonatomic,copy ) NSString *title;
@property(nonatomic,assign ) UIAlertActionStyle  style;
@end

@implementation LZAlertActionModel
- (instancetype)init {
    if (self = [super init]) {
        self.title = @"";
        self.style = UIAlertViewStyleDefault;
    }
    return self;
}
@end

#pragma mark - II LZAlertController
/* alertActions 配置 **/
typedef void (^LZAlertAcitionsConfig)(LZAlertActionBlock actionBlock);

@interface LZAlertController()
/* alertActionModel数组 **/
@property(nonatomic,strong) NSMutableArray <LZAlertActionModel *> *alertActionArray;
/* 是否执行动画 **/
@property(nonatomic,assign) BOOL  setAlertAnimated;

/**
 action配置
 */
- (LZAlertAcitionsConfig)alertActionsConfig;

@end

@implementation LZAlertController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.alertDidDismiss) {
        self.alertDidDismiss();
    }
}

#pragma mark - private
- (NSMutableArray<LZAlertActionModel *> *)alertActionArray {
    if (_alertActionArray == nil) {
        _alertActionArray = [NSMutableArray array];
    }
    return _alertActionArray;
}


- (LZAlertAcitionsConfig)alertActionsConfig {
    return ^(LZAlertActionBlock actionBlock){
        if (self.alertActionArray.count>0) {
            //创建alertAction
            __weak typeof(self)weakSelf = self;
            [self.alertActionArray enumerateObjectsUsingBlock:^(LZAlertActionModel * actionModel, NSUInteger idx, BOOL * _Nonnull stop) {
                UIAlertAction *alertAction = [UIAlertAction actionWithTitle:actionModel.title style:actionModel.style handler:^(UIAlertAction * _Nonnull action) {
                    __strong typeof(weakSelf)strongSelf = weakSelf;
                    if (actionBlock) {
                        actionBlock(idx,action,strongSelf);
                    }
                }];
                [self addAction:alertAction];
            }];
        
        }
        else
        {
            NSTimeInterval duration = self.toastStyleDuration > 0 ? self.toastStyleDuration : LZAlertShowDurationDefault;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismissViewControllerAnimated:!(self.setAlertAnimated) completion:NULL];
            });
        }

    };
}

#pragma mark - Public
- (instancetype)initAlertControllerWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle {
    if (!(title.length>0) && (message.length>0) && preferredStyle == UIAlertControllerStyleAlert) {
        title = @"";
    }
    self = [[self class] alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    if (!self) return nil;
    
    self.setAlertAnimated = NO;
    return self;
}

- (void)alertAnimateDisabled {
    self.setAlertAnimated = YES;
}

- (LZAlertActionTitle)addActionDefaultTitle {
    return ^(NSString *title){
        LZAlertActionModel *actionModel = [[LZAlertActionModel alloc]init];
        actionModel.title = title;
        actionModel.style = UIAlertActionStyleDefault;
        [self.alertActionArray addObject:actionModel];
        return self;
    };
}


- (LZAlertActionTitle)addActionCancleTitle {
    return ^(NSString *title){
        LZAlertActionModel *actionModel = [[LZAlertActionModel alloc]init];
        actionModel.title = title;
        actionModel.style = UIAlertActionStyleCancel;
        [self.alertActionArray addObject:actionModel];
        return self;
    };
}

- (LZAlertActionTitle)addActionDestructiveTitle {
    return ^(NSString *title){
        LZAlertActionModel *actionModel = [[LZAlertActionModel alloc]init];
        actionModel.title = title;
        actionModel.style = UIAlertActionStyleDestructive;
        [self.alertActionArray addObject:actionModel];
        return self;
    };
}


@end


#pragma mark - III 类别
@implementation UIViewController (LZAlertViewController)

- (void)lz_showAlertWithPreferredStyle:(UIAlertControllerStyle)preferredStyle title:(NSString *)title message:(NSString *)message appearanceProcess:(LZAlertAppearanceProcess)appearanceProcess actionsBlock:(LZAlertActionBlock)actionBlock {
    if (appearanceProcess) {
        LZAlertController *alertMaker = [[LZAlertController alloc]initAlertControllerWithTitle:title message:message preferredStyle:preferredStyle];
        //防止nil
        if (alertMaker == nil) {
            return;
        }
        //加工链:添加alertAction
        appearanceProcess(alertMaker);
        //配置响应
        alertMaker.alertActionsConfig(actionBlock);
        
        if (alertMaker.alertDidShown) {
            [self presentViewController:alertMaker animated:!alertMaker.setAlertAnimated completion:^{
                alertMaker.alertDidShown();
            }];
        }
        else{
            [self presentViewController:alertMaker animated:!alertMaker.setAlertAnimated completion:NULL];
        }
    }
}


- (void)lz_showAlertWithTitle:(NSString *)title message:(NSString *)message appearanceProcess:(LZAlertAppearanceProcess)appearanceProcesss actionsBlock:(LZAlertActionBlock)actionBlock {
    [self lz_showAlertWithPreferredStyle:UIAlertControllerStyleAlert title:title message:message appearanceProcess:appearanceProcesss actionsBlock:actionBlock];
}


- (void)lz_showActionSheetWithTitle:(NSString *)title message:(NSString *)message appearanceProcess:(LZAlertAppearanceProcess)appearanceProcess actionsBlock:(LZAlertActionBlock)actionBlock {
    [self lz_showAlertWithPreferredStyle:UIAlertControllerStyleActionSheet title:title message:message appearanceProcess:appearanceProcess actionsBlock:actionBlock];
}

@end
//调用

[self lz_showAlertWithTitle:@"AlertViewTest" message:@"" appearanceProcess:^(LZAlertController * _Nonnull alertMaker) {
        alertMaker.addActionDefaultTitle(@"默认样式");
        alertMaker.addActionDestructiveTitle(@"警告样式");
        alertMaker.addActionCancleTitle(@"取消样式");
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, LZAlertController * _Nonnull alertSelf) {
        NSLog(@"点击了第%ld个",buttonIndex);
    }];


[self lz_showActionSheetWithTitle:@"SheetViewTest" message:@"" appearanceProcess:^(LZAlertController * _Nonnull alertMaker) {
        alertMaker.addActionDefaultTitle(@"默认样式");
        alertMaker.addActionDestructiveTitle(@"警告样式");
        alertMaker.addActionCancleTitle(@"取消样式");
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, LZAlertController * _Nonnull alertSelf) {
        switch (action.style) {
            case UIAlertActionStyleDefault:
                NSLog(@"默认");
                break;
            case UIAlertActionStyleCancel:
                NSLog(@"取消");
                break;
            case UIAlertActionStyleDestructive:
                NSLog(@"警告");
                break;
                
            default:
                break;
        }
    }];

Gitgub地址 喜欢的朋友打赏个星星,谢谢

上一篇下一篇

猜你喜欢

热点阅读