美文网首页
简单封装UIAlertController 方便使用

简单封装UIAlertController 方便使用

作者: 辰星撒欢的蒜苗 | 来源:发表于2017-11-06 17:08 被阅读34次

    今天看到下面一段代码 ,感觉这代码写的好累🤣🤣🤣。然后就简单的封装一下UIAlertController以方便使用,仅仅只有一个action和两个action的。🤔🤔🤔

    原始代码截图

    修改后代码如下,是不是看着舒服多了🤓🤓🤓

    修改后代码截图

    我是给UIViewController添加了一个category,这样只要是UIViewController里都可以直接调用。

    代码如下:

    #import "UIViewController+AlertVC.h"
    
    @implementation UIViewController (AlertVC)
    
    - (void)presentOneActionAlertControllerTitle:(NSString *_Nullable)aTitle message:(NSString *_Nullable)aMessage actionTitle:(NSString *_Nullable)actionTitle handler:(void (^ _Nullable )(UIAlertAction * _Nullable action))handler {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:aTitle message:aMessage preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *leftAction  = [UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            handler(action);
        }];
        [alert addAction:leftAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    - (void)presentTwoActionAlertControllerTitle:(NSString *_Nullable)aTitle message:(NSString *_Nullable)aMessage rightTitle:(NSString *_Nullable)rightTitle leftTitle:(NSString *_Nullable)leftTitle rightActionStyle:(UIAlertActionStyle)style rightHandler:(void (^ _Nullable )(UIAlertAction * _Nullable action))rightHandler leftHandler:(void (^ _Nullable )(UIAlertAction * _Nullable action))leftHandler {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:aTitle message:aMessage preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *rightAction  =  [UIAlertAction actionWithTitle:rightTitle style:style handler:^(UIAlertAction * _Nonnull action) {
            rightHandler(action);
        }];
        UIAlertAction *leftAction  = [UIAlertAction actionWithTitle:leftTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            leftHandler(action);
        }];
        [alert addAction:rightAction];
        [alert addAction:leftAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    

    大家一起愉快的Alert弹框吧😉😉😉

    相关文章

      网友评论

          本文标题:简单封装UIAlertController 方便使用

          本文链接:https://www.haomeiwen.com/subject/dhvlmxtx.html