实现效果如下:

功能说明:

程序运行,图片自动循环播放,采用定时器实现;

当用户用手势触摸滑动时,定时器的自动播放取消,停止触摸时,自动无限播放;

代码如下 :

采用封装视图,外部进行调用即可:

1.//
//  PSScrollVIew.h
//  ScrollView实现自动循环滚动广告
//
//  Created by mac1 on 15/9/30.
//  Copyright (c) 2015年 www.iphonetrain.com. All rights reserved.
//

#import <UIKit/UIKit.h>

//定义协议

@protocol PSScrollViewViewDelegate <NSObject>

- (void)didClickPage:(id)view atIndex:(NSInteger)index;

@end

@interface PSScrollVIew : UIView<UIScrollViewDelegate>

@property (nonatomic,strong)id<PSScrollViewViewDelegate> delegate;

@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, strong) NSMutableArray *imageViewAry;

@property (nonatomic, readonly) UIScrollView *scrollView;

@property (nonatomic, readonly) UIPageControl *pageControl;

-(void)shouldAutoShow:(BOOL)shouldStart;

@end

2.

//
//  PSScrollVIew.m
//  ScrollView实现自动循环滚动广告
//
//  Created by mac1 on 15/9/30.
//  Copyright (c) 2015年 www.iphonetrain.com. All rights reserved.
//

#import "PSScrollVIew.h"

//延展

@interface PSScrollVIew ()

{
    UIView *_firstView;
    UIView *_middleView;
    UIView *_lastView;
    
    float _viewWidth;
    float _viewHeight;
    
    NSTimer *_autoScrollTimer;
    
    //点击手势
    
    UITapGestureRecognizer *_tap;
}

@end

@implementation PSScrollVIew

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        _viewWidth = self.bounds.size.width;
        _viewHeight = self.bounds.size.height;
        
        //设置scrollview
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _viewWidth, _viewHeight)];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(_viewWidth * 3, _viewHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.backgroundColor = [UIColor blackColor];
        _scrollView.delegate = self;
        [self addSubview:_scrollView];
        
        //设置分页
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, _viewHeight-30, _viewWidth, 30)];
        _pageControl.userInteractionEnabled = NO;
        _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
        [self addSubview:_pageControl];
        
        //设置单击手势
        _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
        _tap.numberOfTapsRequired = 1;
        _tap.numberOfTouchesRequired = 1;
        [_scrollView addGestureRecognizer:_tap];
    }
    return self;
}

#pragma mark 单击手势
-(void)handleTap:(UITapGestureRecognizer*)sender
{
    if ([_delegate respondsToSelector:@selector(didClickPage:atIndex:)]) {
        [_delegate didClickPage:self atIndex:_currentPage+1];
    }
}

#pragma mark 设置imageViewAry
-(void)setImageViewAry:(NSMutableArray *)imageViewAry
{
    if (imageViewAry) {
        _imageViewAry = imageViewAry;
        _currentPage = 0; //默认为第0页
        
        _pageControl.numberOfPages = _imageViewAry.count;
    }
    
    [self reloadData];
}

#pragma mark 刷新view页面
-(void)reloadData
{
    [_firstView removeFromSuperview];
    [_middleView removeFromSuperview];
    [_lastView removeFromSuperview];
    
    //从数组中取到对应的图片view加到已定义的三个view中
    if (_currentPage==0) {
        _firstView = [_imageViewAry lastObject];
        _middleView = [_imageViewAry objectAtIndex:_currentPage];
        _lastView = [_imageViewAry objectAtIndex:_currentPage+1];
    }
    else if (_currentPage == _imageViewAry.count-1)
    {
        _firstView = [_imageViewAry objectAtIndex:_currentPage-1];
        _middleView = [_imageViewAry objectAtIndex:_currentPage];
        _lastView = [_imageViewAry firstObject];
    }
    else
    {
        _firstView = [_imageViewAry objectAtIndex:_currentPage-1];
        _middleView = [_imageViewAry objectAtIndex:_currentPage];
        _lastView = [_imageViewAry objectAtIndex:_currentPage+1];
    }
    
    //设置三个view的frame,加到scrollview上
    _firstView.frame = CGRectMake(0, 0, _viewWidth, _viewHeight);
    _middleView.frame = CGRectMake(_viewWidth, 0, _viewWidth, _viewHeight);
    _lastView.frame = CGRectMake(_viewWidth*2, 0, _viewWidth, _viewHeight);
    [_scrollView addSubview:_firstView];
    [_scrollView addSubview:_middleView];
    [_scrollView addSubview:_lastView];
    
    //设置当前的分页
    _pageControl.currentPage = _currentPage;
    
    //显示中间页
    _scrollView.contentOffset = CGPointMake(_viewWidth, 0);
}

#pragma mark scrollvie停止滑动
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //手动滑动时候暂停自动替换
    [_autoScrollTimer invalidate];
    _autoScrollTimer = nil;
    _autoScrollTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoShowNextImage) userInfo:nil repeats:YES];
    
    //得到当前页数
    float x = _scrollView.contentOffset.x;
    
    //往前翻
    if (x<=0) {
        if (_currentPage-1<0) {
            _currentPage = _imageViewAry.count-1;
        }else{
            _currentPage --;
        }
    }
    
    //往后翻
    if (x>=_viewWidth*2) {
        if (_currentPage==_imageViewAry.count-1) {
            _currentPage = 0;
        }else{
            _currentPage ++;
        }
    }
    
    [self reloadData];
}

#pragma mark 自动滚动
-(void)shouldAutoShow:(BOOL)shouldStart
{
    if (shouldStart)  //开启自动翻页
    {
        if (!_autoScrollTimer) {
            
            //开启定时器
            _autoScrollTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoShowNextImage) userInfo:nil repeats:YES];
        }
    }
    else   //关闭自动翻页
    {
        if (_autoScrollTimer.isValid) {
            
            //关闭定时器
            [_autoScrollTimer invalidate];
            _autoScrollTimer = nil;
        }
    }
}

#pragma mark 展示下一页

-(void)autoShowNextImage
{
    if (_currentPage == _imageViewAry.count-1) {
        _currentPage = 0;
    }else{
        _currentPage ++;
    }
    
    [self reloadData];
}

@end

3.

外部调用:

//
//  ViewController.m
//  ScrollView实现自动循环滚动广告
//
//  Created by mac1 on 15/9/30.
//  Copyright (c) 2015年 www.iphonetrain.com. All rights reserved.
//

#import "ViewController.h"
#import "PSScrollVIew.h"

@interface ViewController ()

@end

#define NUM 4

@interface ViewController ()<PSScrollViewViewDelegate>
{
    PSScrollVIew *_whView;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //创建view (view中包含UIScrollView、UIPageControl,设置frame)
    _whView = [[PSScrollVIew alloc] initWithFrame:CGRectMake(10, 44, 300, 480)];
    
    //把N张图片放到imageview上
    NSMutableArray *tempAry = [NSMutableArray array];
    for (int i=1; i<NUM; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg",i]];
        [tempAry addObject:imageView];
    }
    
    //把imageView数组存到whView里
    [_whView setImageViewAry:tempAry];
    
    //把图片展示的view加到当前页面
    [self.view addSubview:_whView];
    
    //开启自动翻页
    [_whView shouldAutoShow:YES];
    
    //遵守协议
    _whView.delegate = self;
}

#pragma mark 协议里面方法,点击某一页

-(void)didClickPage:(PSScrollVIew *)view atIndex:(NSInteger)index
{
    NSLog(@"点击了第%li页",index);
}

#pragma mark 界面消失的时候,停止自动滚动
-(void)viewDidDisappear:(BOOL)animated
{
    [_whView shouldAutoShow:NO];
}

@end

这个小Demo也是参照了别人的博客写的,如有雷同,纯属学习!!!

UIScrollView实现自动循环滚动广告的更多相关文章

  1. IOS实现自动循环滚动广告--ScrollView的优化和封装

    一.问题分析 在许多App中,我们都会见到循环滚动的视图,比如广告,其实想实现这个功能并不难,用ScrollView就可以轻松完成,但是在制作的过程中还存在几个小问题,如果能够正确的处理好这些小问题, ...

  2. UIScrollView现实自动循环滚动

    #import "RootViewController.h" #define width [UIScreen mainScreen].bounds.size.width #defi ...

  3. 【转】Android循环滚动广告条的完美实现,封装方便,平滑过渡,从网络加载图片,点击广告进入对应网址

    Android循环滚动广告条的完美实现,封装方便,平滑过渡,从网络加载图片,点击广告进入对应网址 关注finddreams,一起分享,一起进步: http://blog.csdn.net/finddr ...

  4. 使用Recyclerview实现图片水平自动循环滚动

    简介: 本篇博客主要介绍的是如何使用RecyclerView实现图片水平方向自动循环(跑马灯效果) 效果图: 思路: 1.准备m张图片 1.使用Recyclerview实现,返回无数个(实际Inter ...

  5. 自动循环滚动ScrollView

    // // SBCycleScrollView.h // SBCycleScrollView // // Created by luo.h on 15/7/12. // Copyright (c) 2 ...

  6. ListView的自动循环滚动显示

    最近项目里需要做评价内容的循环滚动显示,一开始想到的就是定时器.后来查了资料才知道ListView里面有个函数smoothScrollToPosition(position),瞬间觉得简单了很多.首先 ...

  7. item上下自动循环滚动显示

    //li 上下滚动 (function($){ $.fn.extend({ Scroll:function(opt,callback){ //参数初始化 if(!opt) var opt={}; va ...

  8. IOS无限自动循环滚动banner(源码)

    本文转载至 http://blog.csdn.net/iunion/article/details/19080259  目前有很多APP都开始使用一些滚动banner,我自己也做了一个,部分算法没有深 ...

  9. APP中常见上下循环滚动通知的简单实现,点击可进入详情

    APP中常见上下循环滚动通知的简单实现,点击可进入详情 关注finddreams博客,一起分享一起进步!http://blog.csdn.net/finddreams/article/details/ ...

随机推荐

  1. webpack 配置react脚手架(三):eslint 及优化

    首先谨记 eslint的官网:  http://eslint.cn/ 1 安装eslint  npm i eslint -D 2.在根目录下新建文件 .eslintrc { "extends ...

  2. [NOI2005]月下柠檬树

    题意 F.A.Qs Home Discuss ProblemSet Status Ranklist Contest 入门OJ ModifyUser  autoint Logout 捐赠本站 Probl ...

  3. 创建型模式(一) 单例模式(Singleton)

    一.动机(Motivation) 在软件系统中,经常有这样一些特殊的类,必须保证它们在系统中只存在一个实例,才能确保它们的逻辑正确性.以及良好的效率. 如何绕过常规的构造器,提供一种机制来保证一个类只 ...

  4. GitHub常用命令及使用

    GitHub使用介绍 摘要: 常用命令: git init 新建一个空的仓库git status 查看状态git add . 添加文件git commit -m '注释' 提交添加的文件并备注说明gi ...

  5. 59、servlet3.0-异步请求

    59.servlet3.0-异步请求 59.1 开启servlet异步请求步骤 支持异步处理 asyncSupported=true 开启异步模式 req.startAsync(); 业务逻辑进行异步 ...

  6. Devtool-Console

    1. console面板展示 1.全屏展示 打开开发者工具(option+cmd+i),点击console的tab 2. 在其他面板展示的同时展示console面板 1)esc快捷命令 2)或者选择打 ...

  7. 四十七.iptables防火墙 filter表控制 扩展匹配 nat表典型应用

    1.iptables基本管理 关闭firewalld,开启iptables服务 查看防火墙规则 追加.插入防火墙规则 删除.清空防火墙规则   1.1 关闭firewalld,启动iptables服务 ...

  8. 百度UEditor编辑器从word粘贴公式

    官网地址http://ueditor.baidu.com Git 地址 https://github.com/fex-team/ueditor 参考博客地址 http://blog.ncmem.com ...

  9. exam9.6&&7

    emmm 改题稍紧张,以后几篇并一起写 9.6 (前十并没有参加本次考试) 于是我就rank8了 一道题一道题来 先说T1: 显然是一个高精度GCD,于是打算用计算器算一下时间复杂度 众所周知gcd是 ...

  10. [Luogu] 教主的魔法

    https://www.luogu.org/problemnew/show/P2801 分块 对于每一块进行排序存储在另一个数组中 二分查询 #include<iostream> #inc ...