IOS實現自動循環滾動廣告--ScrollView的優化和封裝

1、問題分析

  在許多App中,咱們都會見到循環滾動的視圖,好比廣告,其實想實現這個功能並不難,用ScrollView就能夠輕鬆完成,可是在製做的過程當中還存在幾個小問題,若是可以正確的處理好這些小問題,不管從效果仍是性能上都會獲得優化。web

問題一

  第一個問題是如何用ScrollView來展現N個視圖。想要實現這個效果,能夠把N個視圖依次按順序添加到ScrollView上,而後把 ScrollView的contentSize設置爲N個視圖的尺寸,經過滑動ScrollView來查看加在上面的視圖。數組

問題二

  第二個問題是如何完成圖片的循環滾動,也就是展現完最後一張以後會接着展現第一張,造成圖片的循環展現。想要實現這個效果,首先須要讓ScrollView實現自動分頁,這樣能夠保證滑動結束展現的是完整的視圖;其次,須要根據當前展現的頁數來設置ScrollView的contentOffset。app

  對於第一個問題的解決是用的最簡單的方式,但實際上忽略了一個很重要的問題,那就是若是要展現的視圖數量N很是大的時候,咱們該如何作呢?假設經過ScrollView來展現的每一個視圖的寬度剛好是屏幕的寬度,那麼在展現的時候,其實可以呈如今咱們眼前的最多隻有兩個視圖,也就是要麼是完整的一個視圖,要麼是兩個不完整的視圖。所以,咱們只須要有三個視圖,就可以完成循環的展現。性能

問題三

  第三個問題是在循環滾動的過程當中,但願知道當前的頁數,這個頁數能夠經過contentOffset.x來計算,一般會用UIPageControl來表示。此外,當點擊某一個視圖的時候,要可以知道當前點擊的視圖是哪個。優化

問題四

  第四個問題是自動展現下一頁的功能,這個須要寫好跳到下一頁的方法,而後經過NSTimer定時器來完成。ui

  除了上面的幾個問題,你們也能夠爲其添加更多的功能。那麼對於ScrollView自動翻頁這樣通用的功能,最好的方式是將其封裝起來,這樣能夠大大的提升效率。下面的代碼是把UIScrollView、UIPageControl封裝到了一個UIView中,而其中的ScrollView用來循環展現多張圖片。atom

2、功能實現

一、封裝Scrollview代碼.h:

//  WHScrollAndPageView.h
//  循環滾動視圖
//
//  Created by jereh on 15-3-15.
//  Copyright (c) 2015年 jereh. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol WHcrollViewViewDelegate;

@interface WHScrollAndPageView : UIView <UIScrollViewDelegate>
{
    __unsafe_unretained id <WHcrollViewViewDelegate> _delegate;
}

@property (nonatomic, assign) id <WHcrollViewViewDelegate> 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

@protocol WHcrollViewViewDelegate <NSObject>

@optional
- (void)didClickPage:(WHScrollAndPageView *)view atIndex:(NSInteger)index;

@end

二、封裝Scrollview代碼.m:

//  WHScrollAndPageView.m
//  循環滾動視圖
//
//  Created by jereh on 15-3-15.
//  Copyright (c) 2015年 jereh. All rights reserved.
//

#import "WHScrollAndPageView.h"

@interface WHScrollAndPageView ()
{
    UIView *_firstView;
    UIView *_middleView;
    UIView *_lastView;
    
    float _viewWidth;
    float _viewHeight;
    
    NSTimer *_autoScrollTimer;
    
    UITapGestureRecognizer *_tap;
}

@end

@implementation WHScrollAndPageView

- (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

三、使用封裝好的Scrollview代碼.m:

//  ViewController.m
//  循環滾動視圖
//
//  Created by jereh on 15-3-15.
//  Copyright (c) 2015年 jereh. All rights reserved.
//

#import "ViewController.h"
#import "WHScrollAndPageView.h"
#define NUM 10

@interface ViewController ()<WHcrollViewViewDelegate>
{
    WHScrollAndPageView *_whView;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //建立view (view中包含UIScrollView、UIPageControl,設置frame)
    _whView = [[WHScrollAndPageView alloc] initWithFrame:CGRectMake(0, 44, 320, 400)];
    
    //把N張圖片放到imageview上
    NSMutableArray *tempAry = [NSMutableArray array];
    for (int i=1; i<NUM; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"image%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:(WHScrollAndPageView *)view atIndex:(NSInteger)index
{
    NSLog(@"點擊了第%li頁",index);
}

#pragma mark 界面消失的時候,中止自動滾動
-(void)viewDidDisappear:(BOOL)animated
{
    [_whView shouldAutoShow:NO];
}

@end

 

做者: 傑瑞教育
出處: http://www.cnblogs.com/jerehedu/ 
本文版權歸煙臺傑瑞教育科技有限公司和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。
相關文章
相關標籤/搜索