iOS|iOS 写一个弹框基类 (baseAlert)

弹框是一个应用必不可少的控件,但是光是用系统丑丑的弹框,往往不能满足我们的需求,很多时候我们需要做一个自定义的弹框,但是 show 和 hide 效果都要统一,那么我就想到来写一个弹框的BaseView.写一个base 弹框baseView 有一个好处,不用重复写一堆如此show 和hide 的效果,写来看怎么使用。
iOS|iOS 写一个弹框基类 (baseAlert)
文章图片
Untitled.gif 1 使用
(1)第一方式继承
继承

iOS|iOS 写一个弹框基类 (baseAlert)
文章图片
7FA9E491-84CA-49E2-B096-898D2A3591DB.png
方法重载

//重载setAlertView把你想要alertView 写出来 -(void)setAlertView { UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 280)]; view.backgroundColor = [UIColor blueColor]; [self addSubview:view]; } // show 执行 -(void)showToDO { NSLog(@"showing ---------"); } //hide执行 -(void)hideToDO { NSLog(@"hiding -----------"); }

【iOS|iOS 写一个弹框基类 (baseAlert)】(2)第二种方式 是直接使用baseAlert 初始化函数
/** *初始化 * *@param type中部alert 还是底部alert *@param isNav 是否包含导航栏 *@param setUIAlertBlock 设置alertView *@param showUIBlock显示alertView *@param hideUIBlock隐藏lertView * *@return <#return value description#> */ -(instancetype)initWithType:(DTAlertType)type andWithNav:(BOOL)nav andSetUIAlert:(alertBlock)setUIAlertBlock andShowUIBlock:(alertBlock)showUIBlock andHideUIBlock:(alertBlock)hideUIBlock; //例子 DTBaseAlertView *alertView = [[ DTBaseAlertView alloc]initWithType:DTAlertTypeBottom andWithNav:NO andSetUIAlert:^(UIView *superView){ UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 280)]; view.backgroundColor = [UIColor blueColor]; [superView addSubview:view]; } andShowUIBlock:^(UIView *superView){ NSLog(@"showing---"); } andHideUIBlock:^(UIView *superView){ NSLog(@"hideing ----"); }]; [self.view addSubview:alertView]; [alertView show];

2 简单代码分析
UIView *bgView = self.subviews[0]; UIView *alertView = self.subviews[1]; bgView.alpha = 0; CGRect frame = alertView.frame; frame.origin.y = ScreenHeight; alertView.frame = frame; [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:2 options:UIViewAnimationOptionCurveEaseIn animations:^{ if (alertType == DTAlertTypeCenter) { CGRect frame = alertView.frame; frame.origin.x = (ScreenWidth - alertView.frame.size.width)/2; frame.origin.y = (ScreenHeight-alertView.frame.size.height)/2; alertView.frame = frame; } if (alertType == DTAlertTypeBottom) { CGRect frame = alertView.frame; frame.origin.x = (ScreenWidth - alertView.frame.size.width)/2; float y = ScreenHeight-alertView.frame.size.height; if (isNav) { y = ScreenHeight-64-alertView.frame.size.height; } frame.origin.y = y; alertView.frame = frame; } bgView.alpha = 0.5; } completion:nil];

主要是通过superview 的 subview 数组获取到alertView(弹框) 然后在对通过uiviewanimation 对他做 frame 改变的过渡动画
例子可以看我的github 地址https://github.com/heysunnyboy/BaseAlert.git

    推荐阅读