彈框是一個應(yīng)用必不可少的控件,但是光是用系統(tǒng)丑丑的彈框垦藏,往往不能滿足我們的需求,很多時候我們需要做一個自定義的彈框,但是 show 和 hide 效果都要統(tǒng)一阐肤,那么我就想到來寫一個彈框的BaseView.寫一個base 彈框baseView 有一個好處,不用重復(fù)寫一堆如此show 和hide 的效果推捐,寫來看怎么使用沼撕。
Untitled.gif
1 使用
(1)第一方式繼承
繼承
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 執(zhí)行
-(void)showToDO
{
NSLog(@"showing ---------");
}
//hide執(zhí)行
-(void)hideToDO
{
NSLog(@"hiding -----------");
}
(2)第二種方式 是直接使用baseAlert 初始化函數(shù)
/**
* 初始化
*
* @param type 中部alert 還是底部alert
* @param isNav 是否包含導(dǎo)航欄
* @param setUIAlertBlock 設(shè)置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 數(shù)組獲取到alertView(彈框) 然后在對通過uiviewanimation 對他做 frame 改變的過渡動畫
例子可以看我的github 地址https://github.com/heysunnyboy/BaseAlert.git