今天分享一下仿滴滴打車的廣告彈窗,效果圖如下:

實(shí)現(xiàn)的思路:自定義ADAlertView(繼承自UIView),然后添加scrollView,scrollView上布局五個(gè)自定義的小view(ADItemView)來(lái)支持滑動(dòng),然后再添加pageControl和關(guān)閉按鈕。
代碼下載鏈接已經(jīng)在底部貼出來(lái),可以去github下載。
下面主要就代碼中的一些細(xì)節(jié)做一些描述。?
廣告彈窗視圖ADAlertView初始化方法
+(ADAlertView *)showInView:(UIView *)view theDelegate:(id)delegate theADInfo: (NSArray *)dataList placeHolderImage: (NSString *)placeHolderStr;
需要注意一點(diǎn),廣告框是加載到keyWindow上的
[[[UIApplication sharedApplication].windows objectAtIndex:0] addSubview:self];
廣告點(diǎn)擊事件是通過(guò)添加點(diǎn)擊手勢(shì)來(lái)實(shí)現(xiàn)如下方法
-(void)tapContentImgView:(UITapGestureRecognizer *)gesture
然后通過(guò)代理方法實(shí)現(xiàn)跳轉(zhuǎn)url廣告鏈接。
-(void)clickAlertViewAtIndex:(NSInteger)index;
ADItemView為廣告圖片控件,對(duì)其layer層操作實(shí)現(xiàn)圓角效果
ADModel為數(shù)據(jù)源模型,通過(guò)點(diǎn)擊不同的index來(lái)調(diào)用數(shù)據(jù)源對(duì)象,實(shí)現(xiàn)跳轉(zhuǎn)。
滑動(dòng)scrollView的時(shí)候更改index,調(diào)用pageControl的代理方法。
#pragma mark - UIScrollViewDelegate? 滑動(dòng)scrollView 切換pageContrl
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSInteger index? ? ? ? = scrollView.contentOffset.x/ScreenWidth;
pageControl.currentPage = index;
}
在pageControl代理方法中實(shí)現(xiàn)scrollView分頁(yè)滑動(dòng)效果。
/// 當(dāng)pageControl改變的時(shí)候,判斷scrollView偏移
-(void)pageValueChange:(UIPageControl*)page{
[UIView animateWithDuration:.35 animations:^{
_scrollView.contentOffset = CGPointMake(page.currentPage*ScreenWidth, 0);
}];
}
點(diǎn)擊移除廣告彈框是通過(guò)手勢(shì)調(diào)用如下方法
-(void)removeFromCurrentView:(UIGestureRecognizer *)gesture;
移除彈窗方法如下
/// 移除廣告
- (void)removeSelfFromSuperview
{
[UIView animateWithDuration:0.2 animations:^{
self.alpha = 0;
} completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}
為了更好的用戶提樣,在彈處廣告框的時(shí)候添加一個(gè)透明度過(guò)渡動(dòng)畫(huà)。
/// 透明度動(dòng)畫(huà)
- (void)showAlertAnimation
{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
animation.fromValue? ? ? ? = [NSNumber numberWithFloat:0];
animation.toValue? ? ? ? ? = [NSNumber numberWithFloat:1];
animation.duration? ? ? ? ? = 0.5;
animation.timingFunction? ? = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[self.layer addAnimation:animation forKey:@"opacity"];
}
github下載鏈接:https://github.com/IT-iOS-xie/didiAdAlertView.git