今天分享一下仿滴滴打車的廣告彈窗泡垃,效果圖如下:
實現(xiàn)的思路:自定義ADAlertView(繼承自UIView)炸站,然后添加scrollView姑原,scrollView上布局五個自定義的小view(ADItemView)來支持滑動箕速,然后再添加pageControl和關(guān)閉按鈕。
代碼下載鏈接已經(jīng)在底部貼出來奇唤,可以去github下載。
下面主要就代碼中的一些細節(jié)做一些描述匹摇。?
廣告彈窗視圖ADAlertView初始化方法
+(ADAlertView *)showInView:(UIView *)view theDelegate:(id)delegate theADInfo: (NSArray *)dataList placeHolderImage: (NSString *)placeHolderStr;
需要注意一點,廣告框是加載到keyWindow上的
[[[UIApplication sharedApplication].windows objectAtIndex:0] addSubview:self];
廣告點擊事件是通過添加點擊手勢來實現(xiàn)如下方法
-(void)tapContentImgView:(UITapGestureRecognizer *)gesture
然后通過代理方法實現(xiàn)跳轉(zhuǎn)url廣告鏈接甲葬。
-(void)clickAlertViewAtIndex:(NSInteger)index;
ADItemView為廣告圖片控件廊勃,對其layer層操作實現(xiàn)圓角效果
ADModel為數(shù)據(jù)源模型,通過點擊不同的index來調(diào)用數(shù)據(jù)源對象经窖,實現(xiàn)跳轉(zhuǎn)坡垫。
滑動scrollView的時候更改index,調(diào)用pageControl的代理方法画侣。
#pragma mark - UIScrollViewDelegate? 滑動scrollView 切換pageContrl
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSInteger index? ? ? ? = scrollView.contentOffset.x/ScreenWidth;
pageControl.currentPage = index;
}
在pageControl代理方法中實現(xiàn)scrollView分頁滑動效果冰悠。
/// 當(dāng)pageControl改變的時候,判斷scrollView偏移
-(void)pageValueChange:(UIPageControl*)page{
[UIView animateWithDuration:.35 animations:^{
_scrollView.contentOffset = CGPointMake(page.currentPage*ScreenWidth, 0);
}];
}
點擊移除廣告彈框是通過手勢調(diào)用如下方法
-(void)removeFromCurrentView:(UIGestureRecognizer *)gesture配乱;
移除彈窗方法如下
/// 移除廣告
- (void)removeSelfFromSuperview
{
[UIView animateWithDuration:0.2 animations:^{
self.alpha = 0;
} completion:^(BOOL finished) {
[self removeFromSuperview];
}];
}
為了更好的用戶提樣溉卓,在彈處廣告框的時候添加一個透明度過渡動畫。
/// 透明度動畫
- (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