1. 程式人生 > >iOS開發之多圖片無縫滾動元件封裝與使用

iOS開發之多圖片無縫滾動元件封裝與使用

正兒八經的圖片滾動的Demo我這兒還真沒有,今天呢就封裝一個可以在專案中直接使用的圖片輪播。沒看過其他iOS圖片無限輪播的程式碼,也不瞭解他們的原理,我今天封裝這個圖片無限輪播是借鑑Web前端中的做法,因為之前寫Web前端的時候,實現幻燈片就是這麼做的,今天就在iPhone上搞搞。下面的東西是自己寫的了,關於輪播的東西這個開源專案也是相當不錯的h ttps://gi thub.com / nicklockwood / iCarousel ,感興趣的可以看一下。那是相當的強大,雖然沒必要重複造輪子但是原理還是有必要理解的。今天的部落格就介紹圖片輪播的一種解決方案,下篇部落格中在介紹另一種圖片輪播的解決方案。

  一、Demo執行效果、原理及呼叫方式

    1.執行效果

    下面的GIF呢就是Demo的執行效果,一定間隔後,圖片會自動切換,當然也支援手指滑動。切換到相應圖片時,點選圖片,會通過Block回撥的方式給出該圖片的Index, 在Demo中使用提示框給出Index, 當然在專案中拿到Index你可以做很多事情的,Index就是圖片的Tag值,也就是標記著你點選的是那張圖片。下圖中是三張圖片進行輪播。

  2.原理

  下面是實現圖片無限輪播的原理圖(借鑑Web前端幻燈片的寫法,歡迎大家提出好的解決方案),原理用一句話概括:如果顯示3張圖片的話,就往ScrollView上貼4張圖順序是3-1-2-3。首次顯示1的位置,然後滑動,等滑動到最後一個3時,無動畫切換到第一個3的位置,然後在滾動。原理圖如下,就可以按著下面的原理圖來佈局和例項化控制元件了。

  3.元件呼叫方式

    下面這段程式碼是元件的初始化和屬性的設定,分為如下幾部:

      (1):確定元件的位置

      (2):生成圖片名字陣列

      (3):通過便利構造器初始化控制元件,並傳入imageName陣列

      (4):設定屬性(可選), scrollInterval-圖片切換間隔,animationInterVale-圖片運動時間

      (5):addTapEventForImageWithBlock:圖片點選後的回撥

複製程式碼
 1 -(void) addZLImageViewDisPlayView{
 2     
 3     //
獲取要顯示的位置 4 CGRect screenFrame = [[UIScreen mainScreen] bounds]; 5 6 CGRect frame = CGRectMake(10, 60, screenFrame.size.width - 20, 200); 7 8 NSArray *imageArray = @[@"01.jpg", @"02.jpg", @"03.jpg"]; 9 10 //初始化控制元件 11 ZLImageViewDisplayView *imageViewDisplay = [ZLImageViewDisplayView zlImageViewDisplayViewWithFrame:frame WithImages:imageArray]; 12 13 //設定輪播時間 14 imageViewDisplay.scrollInterval = 2; 15 16 //圖片滾動的時間 17 imageViewDisplay.animationInterVale = 0.6; 18 19 //把該檢視新增到相應的父檢視上 20 [self.view addSubview:imageViewDisplay]; 21 22 [imageViewDisplay addTapEventForImageWithBlock:^(NSInteger imageIndex) { 23 NSString *str = [NSString stringWithFormat:@"我是第%ld張圖片", imageIndex]; 24 UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 25 [alter show]; 26 }]; 27 28 }
複製程式碼

  二、核心程式碼介紹

    1.元件的便利初始化方法如下,傳入的引數是元件的frame, 和要顯示的圖片名字陣列。在便利初始化方法中初始化一些屬性和呼叫相關初始化方法。初始化內容如下:

複製程式碼
 1 #pragma -- mark 遍歷初始化方法
 2 - (instancetype)initWithFrame: (CGRect)frame
 3                WithImages: (NSArray *) images
 4 {
 5     self = [super initWithFrame:frame];
 6     if (self) {
 7         //獲取滾動檢視的寬度
 8         _widthOfView = frame.size.width;
 9         
10         //獲取滾動檢視的高度
11         _heightView = frame.size.height;
12         
13         _scrollInterval = 3;
14         
15         _animationInterVale = 0.7;
16         
17         //當前顯示頁面
18         _currentPage = 1;
19         
20         _imageViewcontentModel = UIViewContentModeScaleAspectFill;
21         
22         self.clipsToBounds = YES;
23         
24         //初始化滾動檢視
25         [self initMainScrollView];
26         
27         //新增ImageView
28         [self addImageviewsForMainScrollWithImages:images];
29         
30         //新增timer
31         [self addTimerLoop];
32         
33         [self addPageControl];
34         
35     }
36     return self;
37 }
複製程式碼

    2.便利構造器

    為我們的元件新增上便利構造器,便利構造器當然是類方法了,傳的引數和便利初始化方法一樣,該方法主要就是類的初始化,然後呼叫便利初始化方法, 並返回類的物件。程式碼如下:

複製程式碼
#pragma -- 便利構造器
+ (instancetype) zlImageViewDisplayViewWithFrame: (CGRect) frame
                                      WithImages: (NSArray *) images{
    ZLImageViewDisplayView *instance = [[ZLImageViewDisplayView alloc] initWithFrame:frame WithImages:images];
    return instance;
}
複製程式碼

    3.初始化ScrollView

    往我們自定義元件檢視上新增ScrollView, ScrollView的的大小和我們自定義元件的大小一樣,並且設定相關屬性,設定代理方法,程式碼如下:

複製程式碼
 1 #pragma -- mark 初始化ScrollView
 2 - (void) initMainScrollView{
 3     
 4     _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _widthOfView, _heightView)];
 5     
 6     _mainScrollView.contentSize = CGSizeMake(_widthOfView, _heightView);
 7     
 8     _mainScrollView.pagingEnabled = YES;
 9     
10     _mainScrollView.showsHorizontalScrollIndicator = NO;
11     
12     _mainScrollView.showsVerticalScrollIndicator = NO;
13     
14     _mainScrollView.delegate = self;
15     
16     [self addSubview:_mainScrollView];
17 }
複製程式碼

    4.新增PageControl

      初始化PageControl, 配置相關屬性,並新增到我們的自定義元件上,程式碼如下:

複製程式碼
 1 #pragma 新增PageControl
 2 - (void) addPageControl{
 3     _imageViewPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, _heightView - 20, _widthOfView, 20)];
 4     
 5     _imageViewPageControl.numberOfPages = _imageViewArray.count;
 6     
 7     _imageViewPageControl.currentPage = _currentPage - 1;
 8     
 9     _imageViewPageControl.tintColor = [UIColor blackColor];
10     
11     [self addSubview:_imageViewPageControl];
12 }
複製程式碼

    5.新增ImageView和Image

    往ScrollView上新增ImageView和Image, 下面這個方法也是核心程式碼,我們根據是第幾張圖片來計算圖片的Frame進行佈局,每張圖片的大小就是我們元件的大小,根據上面原理的介紹,ScrollView上的第一張圖片和最後一張圖片一樣,你想顯示的第一張圖片放到ScrollView上的第二張,並改變Scollview的Contentoffset顯示ScrollView上的第二張圖片,程式碼如下:

複製程式碼
 1 #pragma -- mark 給ScrollView新增ImageView
 2 -(void) addImageviewsForMainScrollWithImages: (NSArray *) images{
 3     //設定ContentSize
 4     _mainScrollView.contentSize = CGSizeMake(_widthOfView * (images.count+1), _heightView);
 5     
 6     _imageViewArray = images;
 7     
 8     for ( int i = 0; i < _imageViewArray.count + 1; i ++) {
 9         
10         CGRect currentFrame = CGRectMake(_widthOfView * i, 0, _widthOfView, _heightView);
11         
12         UIImageView *tempImageView = [[UIImageView alloc] initWithFrame:currentFrame];
13         
14         tempImageView.contentMode = _imageViewcontentModel;
15         
16         tempImageView.clipsToBounds = YES;
17         
18         NSString *imageName;
19         
20         if (i == 0) {
21             imageName = [_imageViewArray lastObject];
22         } else {
23             imageName = _imageViewArray[i - 1];
24         }
25         
26         UIImage *imageTemp = [UIImage imageNamed:imageName];
27         [tempImageView setImage:imageTemp];
28         
29         [_mainScrollView addSubview:tempImageView];
30     }
31     
32     _mainScrollView.contentOffset = CGPointMake(_widthOfView, 0);
33     
34 }
複製程式碼

    6.新增定時器

    想讓圖片自己動起來,是少不了定時器的,為我們的元件新增定時器,下面的方法就是初始化定時器方法:

複製程式碼
1 - (void) addTimerLoop{
2     
3     if (_timer == nil) {
4         _timer = [NSTimer scheduledTimerWithTimeInterval:_scrollInterval target:self selector:@selector(changeOffset) userInfo:nil repeats:YES];
5     }
6 }
複製程式碼

    7.定時器執行的方法

    下面的方法就是定時器執行的方法,當時間到時,自動改變ScrollView的ContentOffset.x的值,有動畫的切換到下一張圖片。如果目前是最後一張圖片則無動畫的切換到ScrollView的第一張圖片,因為第一張圖片和最後一張圖片是一樣的,所以使用者看不到這個無動畫的切換,切換後,圖片有開始從第一個開始滾動,所以就可以無限迴圈的滾動了,下面也是核心程式碼:

複製程式碼
 1 -(void) changeOffset{
 2     
 3     _currentPage ++;
 4     
 5     if (_currentPage == _imageViewArray.count + 1) {
 6         _currentPage = 1;
 7     }
 8     
 9     [UIView animateWithDuration:_animationInterVale animations:^{
10         _mainScrollView.contentOffset = CGPointMake(_widthOfView * _currentPage, 0);
11     } completion:^(BOOL finished) {
12         if (_currentPage == _imageViewArray.count) {
13             _mainScrollView.contentOffset = CGPointMake(0, 0);
14         }
15     }];
16     
17      _imageViewPageControl.currentPage = _currentPage - 1;
18     
19 }
複製程式碼

    8.手動切換

    上面介紹的是使用NSTimer來實現自動切換,那麼如何讓元件支援手動切換呢? 要支援手動切換就得在我們ScrollView的回撥中進行處理了。在使用者手動滑動後的方法中去做我們要做的事情,也就是判斷是不是最後一張圖片,然後在暫停一下定時器即可,對應的回撥方法如下:

複製程式碼
 1 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
 2     NSInteger currentPage = scrollView.contentOffset.x / _widthOfView;
 3     
 4     if(currentPage == 0){
 5         _mainScrollView.contentOffset = CGPointMake(_widthOfView * _imageViewArray.count, 0);
 6         _imageViewPageControl.currentPage = _imageViewArray.count;
 7         _currentPage = _imageViewArray.count;
 8     }
 9     
10     if (_currentPage + 1 == currentPage || currentPage == 1) {
11         _currentPage = currentPage;
12         
13         if (_currentPage == _imageViewArray.count + 1) {
14             _currentPage = 1;
15         }
16         
17         if (_currentPage == _imageViewArray.count) {
18             _mainScrollView.contentOffset = CGPointMake(0, 0);
19         }
20         
21         _imageViewPageControl.currentPage = _currentPage - 1;
22         [self resumeTimer];
23         return;
24     }
25     
26     
27 }
複製程式碼

    9.暫停定時器

    手動滑動後要暫停定時器一段時間,因為不暫停的話,你手動切換完,有時會立刻切換到下一張圖片,下面是暫停定時器的方法,然後在過一段時間後自動啟用定時器。方法如下

複製程式碼
 1 #pragma 暫停定時器
 2 -(void)resumeTimer{
 3     
 4     if (![_timer isValid]) {
 5         return ;
 6     }
 7     
 8     [_timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:_scrollInterval-_animationInterVale]];
 9     
10 }
複製程式碼

    經過上面的這些程式碼元件就可以被呼叫了,你的圖片就可以使用了,最後在給出該元件留出的對外介面:

複製程式碼
 1 //
 2 //  ZLImageViewDisplayView.h
 3 //  ZLImageViewDisplay
 4 //
 5 //  Created by Mr.LuDashi on 15/8/14.
 6 //  Copyright (c) 2015年 ludashi. All rights reserved.
 7 //
 8 
 9 #import <UIKit/UIKit.h>
10 
11 //點選圖片的Block回撥,引數當前圖片的索引,也就是當前頁數
12 typedef void(^TapImageViewButtonBlock)(NSInteger imageIndex);
13 
14 @interface ZLImageViewDisplayView : UIView
15 
16 
17 //切換圖片的時間間隔,可選,預設為3s
18 @property (nonatomic, assign) CGFloat scrollInterval;
19 
20 //切換圖片時,運動時間間隔,可選,預設為0.7s
21 @property (nonatomic, assign) CGFloat animationInterVale;
22 
23 /**********************************
24  *功能:便利構造器
25  *引數:滾動檢視的Frame, 要顯示圖片的陣列
26  *返回值:該類的物件
27  **********************************/
28 + (instancetype) zlImageViewDisplayViewWithFrame: (CGRect) frame
29                                       WithImages: (NSArray *) images;
30 
31 /**********************************
32  *功能:便利初始化函式
33  *引數:滾動檢視的Frame, 要顯示圖片的陣列
34  *返回值:該類的物件
35  **********************************/
36 - (instancetype)initWithFrame: (CGRect)frame
37                    WithImages: (NSArray *) images;
38 
39 
40 
41 /**********************************
42  *功能:為每個圖片新增點選時間
43  *引數:點選按鈕要執行的Block
44  *返回值:無
45  **********************************/
46 - (void) addTapEventForImageWithBlock: (TapImageViewButtonBlock) block;
47 
48 @end
複製程式碼