ScrollView广告轮播

<span style="background-color: rgb(102, 255, 255);">//
//  AdCollectionViewCell.m
//  LJEAdScrollview
//
//  Created by xiaoyao on 15/4/2.
//  Copyright (c) 2015年 lijien. All rights reserved.
//

//
//  AdCollectionViewCell.h
//  LJEAdScrollview
//
//  Created by xiaoyao on 15/4/2.
//  Copyright (c) 2015年 lijien. All rights reserved.
//

/**
 *  @brief 自定义collectionViewCell,布局每一个广告的现实内容
 *  @author lijien
 */

#import <UIKit/UIKit.h>

@interface AdCollectionViewCell : UICollectionViewCell

// 广告图
@property (nonatomic, strong)  UIImageView *adImageView;

// 图片描述文字
@property (nonatomic, copy)    NSString    *titleString;

@end

#import "AdCollectionViewCell.h"
#import "UIView+UIViewExtension.h"

@implementation AdCollectionViewCell {
  UILabel  *_titleLabel;
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    [self layoutSubviews];
  }

  return self;
}

- (void)setTitleString:(NSString *)titleString {
  _titleString = [titleString copy];
  _titleLabel.text = [NSString stringWithFormat:@"   %@",titleString];
}

- (void)layoutSubviews {
  self.adImageView = [[UIImageView alloc] initWithFrame:self.bounds];

  CGFloat titleW = self.ad_width;
  CGFloat titleH = self.ad_height;
  CGFloat titleX = 0;
  CGFloat titleY = self.ad_height - titleH;

  _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleX, titleY, titleW, titleH)];
  _titleLabel.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
  _titleLabel.font = [UIFont systemFontOfSize:13];
  _titleLabel.textColor = [UIColor whiteColor];
  _titleLabel.hidden = !_titleLabel.text;

  [self addSubview:_adImageView];
  [self addSubview:_titleLabel];
}
@end

//
//  UIView+UIViewExtension.h
//  LJEAdScrollview
//
//  Created by xiaoyao on 15/4/2.
//  Copyright (c) 2015年 lijien. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 *  @brief 每个广告图frame的坐标和宽高
 */
@interface UIView (UIViewExtension)

@property (nonatomic, assign)  CGFloat ad_X;
@property (nonatomic, assign)  CGFloat ad_Y;

@property (nonatomic, assign)  CGFloat ad_width;
@property (nonatomic, assign)  CGFloat ad_height;

@end

//
//  UIView+UIViewExtension.m
//  LJEAdScrollview
//
//  Created by xiaoyao on 15/4/2.
//  Copyright (c) 2015年 lijien. All rights reserved.
//

#import "UIView+UIViewExtension.h"
#import "AdScrollViewFrame.h"

@implementation UIView (UIViewExtension)

- (CGFloat)ad_X {
  return originX;
}

- (CGFloat)ad_Y {
  return originY;
}

- (CGFloat)ad_width {
  return adWidth;
}

- (CGFloat)ad_height {
  return adHeight;
}

- (void)setAd_X:(CGFloat)ad_X {
  CGRect temp = self.frame;
  temp.origin.x = ad_X;
  self.frame = temp;
}

- (void)setAd_Y:(CGFloat)ad_Y {
  CGRect temp = self.frame;
  temp.origin.y = ad_Y;
  self.frame = temp;
}

- (void)setAd_width:(CGFloat)ad_width {
  CGRect temp = self.frame;
  temp.size.width = ad_width;
  self.frame = temp;
}

- (void)setAd_height:(CGFloat)ad_height {
  CGRect temp = self.frame;
  temp.size.height = ad_height;
  self.frame = temp;
}

@end
//
//  AdCycleScrollView.h
//  LJEAdScrollview
//
//  Created by xiaoyao on 15/4/2.
//  Copyright (c) 2015年 lijien. All rights reserved.
//

#import <UIKit/UIKit.h>

@class AdCycleScrollView;

@protocol AdCycleScrollViewDelegate <NSObject>

- (void)cycleScrollView:(AdCycleScrollView *)adScrollView didSelectAtIndex:(NSInteger)index;

@end

/**
 *  @brief 每一个广告视图的布局
 */
@interface AdCycleScrollView : UIView

// 图片数据源
@property (nonatomic, strong) NSArray *imageArray;
// 标题数据源
@property (nonatomic, strong) NSArray *titleArray;
// 时间间隔
@property (nonatomic, assign) CGFloat  autoScrollItemTimeInterval;

@property (nonatomic, assign) NSInteger currentPageIndex;

@property (nonatomic, weak)   id<AdCycleScrollViewDelegate>delegate;

/**
 *  @brief 外部初始化显示广告图的每个collectionView
 */
+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame imagesGroupArray:(NSArray *)imagesArray
                              titleArray:(NSArray *)titleArray;

@end

//
//  AdCycleScrollView.m
//  LJEAdScrollview
//
//  Created by xiaoyao on 15/4/2.
//  Copyright (c) 2015年 lijien. All rights reserved.
//

#import "AdCycleScrollView.h"
#import "AdCollectionViewCell.h"
#import "UIView+UIViewExtension.h"

NSString * const cycleKey = @"cycleKey";

@interface AdCycleScrollView () <UICollectionViewDataSource, UICollectionViewDelegate> {
  UICollectionView *_mainCollectionView;
  UICollectionViewFlowLayout *_flowLayout;
  NSTimer *_timer;
  NSInteger _totalItemCount;
  UIPageControl *_pageControl;
}

@end

@implementation AdCycleScrollView

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];

  if (self) {
    [self layoutMainView];
  }

  return self;
}

+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame imagesGroupArray:(NSArray *)imagesArray titleArray:(NSArray *)titleArray {
  AdCycleScrollView *scroll = [[AdCycleScrollView alloc] initWithFrame:frame];
  scroll.imageArray = imagesArray;
  scroll.titleArray = titleArray;
  return scroll;
}

/**
 *  @beief 设置图片collectionView,以及进行线性布局
 */
- (void)layoutMainView {

  // collectionView的布局
  _flowLayout = [[UICollectionViewFlowLayout alloc] init];
  // 设定全局的cell的frame.size
  _flowLayout.itemSize = self.frame.size;
  // 设定全局的行间距
  _flowLayout.minimumLineSpacing = 0;
  _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

  _mainCollectionView = [[UICollectionView alloc] initWithFrame:self.frame collectionViewLayout:_flowLayout];
  _mainCollectionView.backgroundColor = [UIColor lightGrayColor];
  _mainCollectionView.pagingEnabled = YES;
  _mainCollectionView.showsHorizontalScrollIndicator = NO;
  _mainCollectionView.showsVerticalScrollIndicator = NO;

  // 取消缩放
  _mainCollectionView.bouncesZoom = NO;
  // 取消反弹
  _mainCollectionView.bounces = NO;
  _mainCollectionView.delegate = self;
  _mainCollectionView.dataSource = self;
  [_mainCollectionView registerClass:[AdCollectionViewCell class] forCellWithReuseIdentifier:cycleKey];
  [self addSubview:_mainCollectionView];

  _autoScrollItemTimeInterval = 1.0;
//  _pageControl = [UIPageControl alloc] initWithFrame:CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
}

- (void)setImagesGroup:(NSArray *)imagesGroup
{
  _imageArray = imagesGroup;
  [self setupTimer];
}

/**
 *  @brief 设置定时器
 */
- (void)setupTimer {
  _timer = [NSTimer scheduledTimerWithTimeInterval:self.autoScrollItemTimeInterval
                                            target:self
                                          selector:@selector(automatiocScroll:)
                                          userInfo:nil
                                           repeats:YES];

  // 使用scheduledTimerWithTimeInterval添加到Run Loop中的Timer就不会执行,所以用NSRunLoopCommonModes
  [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)setAutoScrollItemTimeInterval:(CGFloat)autoScrollItemTimeInterval {
  _autoScrollItemTimeInterval = autoScrollItemTimeInterval;
  [_timer invalidate];
  _timer = nil;
  [self setupTimer];
}

- (void)automatiocScroll:(NSTimer *)timer {
  self.currentPageIndex = _mainCollectionView.contentOffset.x / _flowLayout.itemSize.width;
  NSInteger targetPageIndex = self.currentPageIndex + 1;

  if (targetPageIndex == self.imageArray.count) {
     targetPageIndex = self.imageArray.count * 0.5;
    [_mainCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetPageIndex inSection:0]
                                atScrollPosition:UICollectionViewScrollPositionNone
                                        animated:YES];
  }
  [_mainCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetPageIndex inSection:0]
                              atScrollPosition:UICollectionViewScrollPositionNone
                                      animated:YES];
}

#pragma mark - UICollectionViewDataSource
//- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
//  return self.imageArray.count;
//}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  return self.imageArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  AdCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cycleKey forIndexPath:indexPath];
  if (!cell) {
    cell = [[AdCollectionViewCell alloc] init];
  }

  NSUInteger itemIndex = indexPath.item % self.imageArray.count;
  if (self.imageArray.count) {
    cell.adImageView.image = self.imageArray[itemIndex];
  }
  if (self.titleArray.count) {
    cell.titleString = _titleArray[itemIndex];
  }

  return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
  if ([self.delegate respondsToSelector:@selector(cycleScrollView:didSelectAtIndex:)]) {
    [self.delegate cycleScrollView:self didSelectAtIndex:indexPath.item % self.imageArray.count];
  }
}

#pragma mark - UIScrollviewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  NSUInteger index = (scrollView.contentOffset.x + _mainCollectionView.ad_width * 0.5) / _mainCollectionView.ad_width;
  _pageControl.currentPage = index % self.imageArray.count;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  [_timer invalidate];
  _timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  [self setupTimer];
}

@end

//
//  AdScrollViewController.m
//  LJEAdScrollview
//
//  Created by xiaoyao on 15/4/3.
//  Copyright (c) 2015年 lijien. All rights reserved.
//

#import "AdScrollViewController.h"
#import "UIView+UIViewExtension.h"

@interface AdScrollViewController () <AdCycleScrollViewDelegate>

@end

@implementation AdScrollViewController

- (void)viewDidLoad {
    [super viewDidLoad];

  NSArray *images = @[[UIImage imageNamed:@"h1.jpg"],
                      [UIImage imageNamed:@"h2.jpg"],
                      [UIImage imageNamed:@"h3.jpg"],
                      [UIImage imageNamed:@"h4.jpg"]
                      ];

  NSArray *titles = @[@"我的梦想是做一名伟大的产品设计师",
                      @"我的目标是张小龙一样开世界微信产品发布会",
                      @"我可以有丰富多彩的生活除了编程之外",
                      @"谢谢各位,尽情吐槽"
                      ];

  AdCycleScrollView *scroll = [AdCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 60, self.view.frame.size.width, 180)
                                                         imagesGroupArray:images titleArray:titles];
  scroll.titleArray = titles;
  scroll.delegate = self;
  [self.view addSubview:scroll];
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(AdCycleScrollView *)adScrollView didSelectAtIndex:(NSInteger)index
{
  NSLog(@"---点击了第%ld张图片", index);
}

@end
</span>

时间: 2024-10-08 23:21:29

ScrollView广告轮播的相关文章

猫猫学iOS 之广告轮播图,collectionView制作(源码)

猫猫分享,必须精品 原创文章,欢迎转载.转载请注明:翟乃玉的博客 地址:http://blog.csdn.net/u013357243 源码共享:https://github.com/znycat/NYCarouselView 效果图 源代码 NYCarouselView.h // // NYCarouselView.h // 广告轮播CollectionView // // Created by IOS on 15/12/26. // Copyright ? 2015年 com.itcat.c

猫猫学iOS 之广告轮播图,collectionView制作

猫猫分享,必须精品 原创文章,欢迎转载.转载请注明:翟乃玉的博客 地址:http://blog.csdn.net/u013357243 效果图 不多说,好不好先看效果,之前做过一个scrollView的轮播图,但是很局限,很多多余代码,今天猫猫重新做了一个用collectionView的流水布局做的一个,可以拿去做广告轮播,也可以做系统新特性哦,来,看下效果吧. 源码共享:https://github.com/znycat/NYCarouselView 很久很久以前就想做了.总而言之,猫猫代码有

Android 通过ViewFlipper实现广告轮播功能并可以通过手势滑动进行广告切换

为了实现广告轮播功能,在网上找了很多方法,有的效果很好,但是代码太麻烦,并且大多是用的viewpager,总之不是很满意. 于是看了一下sdk有个控件是ViewFlipper,使用比较方便,于是尝试了一下,最终实现了所需效果.在这里与大家分享. 首先看一下效果(主要是布局方面的效果,毕竟手势识别和滑动不太好显示,懒得弄成gif了): 1.布局文件.xml <LinearLayout android:layout_width="fill_parent" android:layout

UIimage两种初始化的区别 广告轮播封装

UIimage两种初始化的区别 第一种初始化: UIImage *image = [UIImage imageNamed:@"xxx"];  注意(这种方法加载的图片如果后缀名是png的,可以不写后缀名,根据屏幕分辨率自己去匹配图片) 第二种初始化: NSString *path = [[NSBundle mainBundle] pathForResource:@"xxx.png" ofType:nil]; UIImage *image = [[UIImage al

广告轮播

1 package com.zxw.fragment; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.UnsupportedEncodingException; 8 import java.util.ArrayList; 9 import java.

android-自定义广告轮播Banner(无限循环实现)

关于广告轮播,大家肯定不会陌生,它在现手机市场各大APP出现的频率极高,它的优点在于"不占屏",可以仅用小小的固定空位来展示几个甚至几十个广告条,而且动态效果很好,具有很好的用户"友好性",下面来看几个示例图:    再来看下我仿写的效果: 关于广告轮播Banner这个东西,GitHub上面应该有现成的开源组件,不过我没去找过,觉得实现起来不会太难,就自己去仿写了,下面我说下实现的思路: 1.首先看到这个可以滑动切换图片的界面,我们很自然就会想到ViewPager控

安卓开发笔记——自定义广告轮播Banner(无限循环实现)

关于广告轮播,大家肯定不会陌生,它在现手机市场各大APP出现的频率极高,它的优点在于"不占屏",可以仅用小小的固定空位来展示几个甚至几十个广告条,而且动态效果很好,具有很好的用户"友好性",下面来看几个示例图:     再来看下我仿写的效果: 关于广告轮播Banner这个东西,GitHub上面应该有现成的开源组件,不过我没去找过,觉得实现起来不会太难,就自己去仿写了,下面我说下实现的思路: 1.首先看到这个可以滑动切换图片的界面,我们很自然就会想到ViewPager

android 项目学习随笔十六( 广告轮播条播放)

广告轮播条播放 if (mHandler == null) {//在此初始化mHandler , 保证消息不重复发送 mHandler = new Handler() { public void handleMessage(android.os.Message msg) { int currentItem = mViewPager.getCurrentItem(); if (currentItem < mTopNewsList.size() - 1) { currentItem++; } els

自定义View(二)ViewPage广告轮播

自定义View的第二个学习案例,使用ViewPage实现广告轮播,通过组合现有的View实现效果如下: 有关ViewPage使用可以学习谷歌官方API,和训练案例: 1.使用ViewPage实现屏幕滑动:https://developer.android.com/training/animation/screen-slide.html 2.API:https://developer.android.com/reference/android/support/v4/view/ViewPager.h