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 <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "DAlertAction.h"

typedef NS_ENUM(NSInteger, AlertAnimationType) {
    AlertAnimationTypeDefault = 0, // 默认动画,如果是SPAlertControllerStyleActionSheet样式,默认动画等效于SPAlertAnimationTypeFromBottom,如果是SPAlertControllerStyleAlert样式,默认动画等效于SPAlertAnimationTypeShrink
    AlertAnimationTypeFromBottom,  // 从底部弹出
    AlertAnimationTypeFromTop,     // 从顶部弹出
    AlertAnimationTypeFromRight,   // 从右边弹出
    AlertAnimationTypeFromLeft,    // 从左边弹出
    
    AlertAnimationTypeShrink,      // 收缩动画
    AlertAnimationTypeExpand,      // 发散动画
    AlertAnimationTypeFade,        // 渐变动画
    
    AlertAnimationTypeNone,        // 无动画
    AlertAnimationTypeAlpha , // 渐变动画
    AlertAnimationTypeRaiseUp, // 从底部弹出
    AlertAnimationTypeDropDown , // 从顶部弹出
};

NS_ASSUME_NONNULL_BEGIN

@interface DAlertView : UIView

/** 主标题 */
@property(nullable, nonatomic, copy) NSString *title;
/** 副标题 */
@property(nullable, nonatomic, copy) NSString *message;
/** 动画类型 */
@property(nonatomic, readonly) AlertAnimationType animationType;
/** 自定义View */
@property (nonatomic, strong) UIView *customAlertView;
/** 主标题颜色 */
@property(nonatomic, strong) UIColor *titleColor;
/** 主标题字体,默认18,加粗 */
@property(nonatomic, strong) UIFont *titleFont;
/** 副标题颜色 */
@property(nonatomic, strong) UIColor *messageColor;
/** 副标题颜色 */
@property(nonatomic, strong) UIColor *lineColor;
/** 副标题字体,默认16,未加粗 */
@property(nonatomic, strong) UIFont *messageFont;
/** 对齐方式(包括主标题和副标题) */
@property(nonatomic, assign) NSTextAlignment textAlignment;

+ (instancetype)alertWithTitle:(NSString *)title message:(NSString *)message;

// 添加action
- (void)addAction:(DAlertAction *)action;

- (void)show;


@end

NS_ASSUME_NONNULL_END
#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] windows] firstObject] 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;
    [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

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

Demo

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏HelloCode开发者学习平台

Core Animation Programming

Core Animation 这个框架实际上非常容易让iOS开发者误解仅仅是用来做动画效果的框架.实际上动画仅仅是是它功能的冰水一角. 它包括了图形绘制,投影,...

10510
来自专栏Android开发经验

flutter混合开发运行报错:VM snapshot must be valid. /Check failed: vm. Must be able to initialize the VM.

找遍了google和flutter github的issue, 目前发现的可行解决办法如下: 1.在flutter module的build文件的andr...

57310
来自专栏业余草

业余草 SpringCloud教程 | 第十篇: 高可用的服务注册中心(Finchley版本)

前面第一篇文章:业余草 SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka(Finchley版本)

10640
来自专栏HelloCode开发者学习平台

多线程学习,从未如此容易

从Apple官网可以看出,我们的主线程在iOS下是 1MB, 在OS X下是 8MB 。如果我们开辟的新的线程则是 512KB

13530
来自专栏流川疯编写程序的艺术

《周鸿祎自述:我的互联网方法论》----摘抄

周鸿祎这个人比较有争议,如果不是他,中国互联网的免费文化可能还不会像今天这样,免费,共享等等概念满天飞。

12640
来自专栏业余草

HTML5中meta属性的使用详解

meta属性在HTML中占据了很重要的位置。如:针对搜索引擎的SEO,文档的字符编码,设置刷新缓存等。虽然一些网页可能没有使用meta,但是作为正规军,我们还是...

20720
来自专栏HelloCode开发者学习平台

iOS开发者多线程学习之旅

说到锁,我们再来看看苹果爸爸的给出干货Synchronization Costs and Performance

9310
来自专栏无原型不设计

新手必看,史上最全的iOS开发教程集锦,没有之一!

最近大火的iPhone XS Max和iPhone XS,不知道有没有同学已经下手了呢?一万三的价位确实让很多人望而却步啊。据说为了赢得中国的用户,专门出了双卡...

15020
来自专栏HelloCode开发者学习平台

逆向开发从零到整(dumpdecrypted砸壳)

https://github.com/stefanesser/dumpdecrypted

26140
来自专栏HelloCode开发者学习平台

RunLoop 妙用,你到现在还不知道????

15520

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励