iOS 一款轻量级的AlertView

系统有AlertController,如果设计师要求不高能满足需求了,但是如果设计师要单独设计一个对话框,在用AlertController就显得有点吃力了,自定义一款吧,GitHub上有很多优秀的开源,杀鸡焉用牛刀,那些大神封装的代码量太多了,出现了个bug自己改要看很久,太多时间浪费在这上面没有必要。还是自己定义一个。

好了废话不多说了还是上代码,很轻量了几百行代码。代码很简单,为了少引用库Masonry都没有使用。

参考了AlertController 首先定义一个DAlertAction

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

typedef NS_ENUM(NSInteger, DAlertActionStyle) {
    DAlertActionStyleDefault = 0,  // 默认样式
    DAlertActionStyleCancel,       // 取消样式
};

NS_ASSUME_NONNULL_BEGIN

@interface DAlertAction : NSObject

/**标题*/
@property (copy, nonatomic) NSString *title;
/**标题字体*/
@property (strong, nonatomic) UIFont *titleFont;
/**标题颜色*/
@property (strong, nonatomic) UIColor *titleColor;
/**回调*/
@property (copy, nonatomic) void (^handler)(DAlertAction *action);
/**Action 式样*/
@property (assign, nonatomic) DAlertActionStyle style;

+ (instancetype)actionWithTitle:(nullable NSString *)title style:(DAlertActionStyle)style handler:(void (^ __nullable)(DAlertAction *action))handler;


@end

NS_ASSUME_NONNULL_END
#import "DAlertAction.h"

@implementation DAlertAction

+ (instancetype)actionWithTitle:(nullable NSString *)title style:(DAlertActionStyle)style handler:(void (^ __nullable)(DAlertAction *action))handler {
    DAlertAction *action = [[self alloc] initWithTitle:title style:(DAlertActionStyle)style handler:handler];
    return action;
}

- (instancetype)initWithTitle:(nullable NSString *)title style:(DAlertActionStyle)style handler:(void (^ __nullable)(DAlertAction *action))handler {
    self = [self init];
    self.title = title;
    self.style = style;
    self.handler = handler;
    
    if (style == DAlertActionStyleDefault) {
        self.titleColor = [UIColor blackColor];
        self.titleFont = [UIFont systemFontOfSize:13.f];
    } else {
        self.titleColor = [UIColor blackColor];
        self.titleFont = [UIFont systemFontOfSize:13.f];
    }
    return self;
}

@end

然后在定义一个DAlertView

#import "DAlertView.h"
#import "UIView+Size.h"

#define kDAlertScreenWidth                [UIScreen mainScreen].bounds.size.width
#define kDAlertScreenHeight               [UIScreen mainScreen].bounds.size.height

const static CGFloat kHeaderViewHeight       = 50;
const static CGFloat kFooterViewHeight       = 50;

const static CGFloat kMessageFontSize               = 14;
const static CGFloat kTitleFontSize               = 18;

@interface DAlertView ()


// action数组
@property (nonatomic, strong) NSMutableArray *actions;
/**头部View*/
@property (nonatomic, strong) UIView *headerView;
/**文本View*/
@property (nonatomic, strong) UIView *contentView;
/**底部View*/
@property (nonatomic, strong) UIView *footerView;
/**对话框View*/
@property (nonatomic, retain) UIView *dialogView;

@end

@implementation DAlertView

- (NSMutableArray *)actions
{
    if (!_actions) {
        _actions = [NSMutableArray array];
    }
    return _actions;
}

+ (instancetype)alertWithTitle:(NSString *)title message:(NSString *)message {
    DAlertView *alertView = [[DAlertView alloc] initWithTitle:title message:message customAlertView:nil customHeaderView:nil customActionSequenceView:nil componentView:nil animationType:AlertAnimationTypeDefault];
    return alertView;
}

- (instancetype)initWithTitle:(nullable NSString *)title message:(nullable NSString *)message customAlertView:(UIView *)customAlertView customHeaderView:(UIView *)customHeaderView customActionSequenceView:(UIView *)customActionSequenceView componentView:(UIView *)componentView  animationType:(AlertAnimationType)animationType {
    self = [self init];
    
    _title = title;
    _message = message;
    _animationType = animationType;
    _customAlertView = customAlertView;
    
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initialize];
    }
    return self;
}

- (void)initialize {
    _titleFont = [UIFont boldSystemFontOfSize:kTitleFontSize];
    _titleColor = [UIColor blackColor];
    _messageFont = [UIFont systemFontOfSize:kMessageFontSize];
    _messageColor = [UIColor grayColor];
    _textAlignment = NSTextAlignmentCenter;
    _lineColor = [UIColor lightGrayColor];
}

// 添加action
- (void)addAction:(DAlertAction *)action {
    [self.actions addObject:action];
}

- (void)show
{
    _dialogView = [self createDialogView];
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    [self addSubview:_dialogView];
     [[[UIApplication sharedApplication] keyWindow] addSubview:self];
}

- (void)dismiss
{
    CATransform3D currentTransform = _dialogView.layer.transform;
    _dialogView.layer.opacity = 1.0f;
    
    __weak typeof(self) weakSelf = self;
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                     animations:^{
                         self.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.0f];
                         weakSelf.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6f, 0.6f, 1.0));
                         weakSelf.dialogView.layer.opacity = 0.0f;
                     }
                     completion:^(BOOL finished) {
                         for (UIView *v in [self subviews]) {
                             [v removeFromSuperview];
                         }
                         [self removeFromSuperview];
                         
                     }
     ];
}


/**
 初始化对话框
 @return 对话框View
 */
- (UIView *)createDialogView
{
    // 获取对话框Size
    CGSize dialogSize = [self getDialogViewSize];
   
    // 设置Frame
    [self setFrame:CGRectMake(0, 0, kDAlertScreenWidth, kDAlertScreenHeight)];
    // 初始化对话框View
     UIView *dialogView = [[UIView alloc] initWithFrame:CGRectMake((kDAlertScreenWidth - dialogSize.width) / 2, (kDAlertScreenHeight - dialogSize.height) / 2, dialogSize.width, dialogSize.height)];
    dialogView.backgroundColor = _lineColor;
    dialogView.layer.masksToBounds = YES;
    dialogView.layer.cornerRadius = 10.;
    
    UIView *headerView = nil;
    if (_title.length > 0) {
        headerView =  [self createHeaderView:CGRectMake(0, 0, dialogSize.width, kHeaderViewHeight)];
        [dialogView addSubview:headerView];
    }
    
    UIView *contentView = [self createContentView: CGRectMake(0, _title.length>0?kHeaderViewHeight+0.5:0, dialogSize.width, [self getContentViewHeight])];
    [dialogView addSubview:contentView];
    
    UIView *footerView = [self createFooterView:CGRectMake(0, contentView.bottom+0.5, dialogSize.width, kFooterViewHeight)];
    [dialogView addSubview:footerView];
    
    return dialogView;
}


/**
 初始化HeaderView
 @return HeaderView
 */
- (UIView *)createHeaderView:(CGRect)frame
{
    // 获取对话框Size
    UIView *headerView = [[UIView alloc]initWithFrame:frame];
    headerView.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.frame = CGRectMake(10, 0, headerView.width-20, headerView.height);
    titleLabel.font = _titleFont?_titleFont:[UIFont systemFontOfSize:kMessageFontSize];
    titleLabel.textColor = _titleColor?_titleColor:[UIColor blackColor];
    titleLabel.text = _title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:titleLabel];
    
    return headerView;
}

/**
 初始化ContentView
 @return ContentView
 */
- (UIView *)createContentView:(CGRect)frame
{
    UIView *contentView = [[UIView alloc]initWithFrame:frame];
    contentView.backgroundColor = [UIColor whiteColor];
    
    UILabel *msgLabel = [UILabel new];
    msgLabel.frame = CGRectMake(10, 10, contentView.width-20, contentView.height-20);
    msgLabel.font = _messageFont?_messageFont:[UIFont systemFontOfSize:kMessageFontSize];
    msgLabel.textColor = _messageColor?_messageColor:[UIColor blackColor];
    msgLabel.text = _message;
    msgLabel.numberOfLines = 0;
    msgLabel.textAlignment = NSTextAlignmentCenter;
    msgLabel.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:msgLabel];
    
    return contentView;
}

/**
 初始化FooterView
 @return FooterView
 */
- (UIView *)createFooterView:(CGRect)frame
{
    UIView *footerView = [[UIView alloc]initWithFrame:frame];
    footerView.backgroundColor = _lineColor;
    
    CGFloat dailogWidth = [self getDialogWidth];
    
    CGFloat btnWidth = dailogWidth/self.actions.count;
    
    for (int i = 0; i < self.actions.count; i++) {
        
        DAlertAction *action = self.actions[i];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(i*btnWidth+i*0.5, 0, btnWidth, kFooterViewHeight);
        [btn setTitle:action.title forState:UIControlStateNormal];
        [btn setTitleColor:action.titleColor forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor whiteColor]];
        btn.tag = i;
        btn.titleLabel.font = action.titleFont;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [footerView addSubview:btn];
    }
    return footerView;
}

- (void)btnAction:(UIButton *)btn
{
    DAlertAction *action = self.actions[btn.tag];
    action.handler(action);
    
    [self dismiss];
}

#pragma Helper

/**
 获取对话框的Size
 @return Size
 */
- (CGSize)getDialogViewSize
{
    CGFloat dialogWidth = [self getDialogWidth];
    
    CGFloat dialogHeight = self.title.length==0? kFooterViewHeight + [self getContentViewHeight]:kHeaderViewHeight + kFooterViewHeight + [self getContentViewHeight];
    
    return CGSizeMake(dialogWidth, dialogHeight);
}

/**
 获取对话框宽度
 @return width
 */
- (CGFloat)getDialogWidth
{
     return kDAlertScreenWidth-80;
}

/**
 获取ContentView高度
 @return height
 */
- (CGFloat)getContentViewHeight
{
    CGSize textSize = [self getTextSize:_message textWidth:[self getDialogWidth]-20 fontSize:_messageFont?_messageFont.pointSize:kMessageFontSize];
    
    CGFloat height = textSize.height + 60 <= kDAlertScreenHeight-180 ? textSize.height + 60 :  kDAlertScreenHeight-180;
    return height;
}

/**
 获取文本Size
 @param string 文本
 @param textWidth 文本宽度
 @param fontSize 字体大小
 @return Size
 */
-(CGSize)getTextSize:(NSString *)string textWidth:(CGFloat)textWidth fontSize:(CGFloat)fontSize{
    UIFont * tfont = [UIFont systemFontOfSize:fontSize];
    // 高度估计文本大概要显示几行,宽度根据需求自己定义。 MAXFLOAT 可以算出具体要多高
    CGSize size =CGSizeMake(textWidth,CGFLOAT_MAX);
    // 获取当前文本的属性
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
    //ios7方法,获取文本需要的size,限制宽度
    CGSize  actualsize =[string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    
    return actualsize;
    
}


@end

使用

DAlertView *alert =[DAlertView alertWithTitle:@"我是一个标题" message:@"文本文本文本文本文本文本文本文本文本文本文本文本文本文"];
    
    DAlertAction *action1 = [DAlertAction actionWithTitle:@"确定" style:DAlertActionStyleDefault handler:^(DAlertAction * _Nonnull action) {
        NSLog(@"点击了确定");
    }];
    
    DAlertAction *action2 = [DAlertAction actionWithTitle:@"取消" style:DAlertActionStyleDefault handler:^(DAlertAction * _Nonnull action) {
        NSLog(@"点击取消");
    }];
    
    alert.titleColor = [UIColor brownColor];
    alert.messageColor = [UIColor blueColor];
    action1.titleColor = [UIColor blueColor];
    action2.titleColor = [UIColor redColor];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [alert show];

效果


Simulator Screen Shot - iPhone XR - 2019-01-16 at 14.05.45.png

Simulator Screen Shot - iPhone XR - 2019-01-16 at 14.07.28.png

Simulator Screen Shot - iPhone XR - 2019-01-17 at 09.15.32.png

这个只是满足基本需求,一般的项目也够用了。需要修改的自己扩展即可!
少重复造轮子了。

Demo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341