iOS 輪播圖

輪播圖幾乎是每一個 App 都會有的功能,而在 UIKit 中又找不到能夠直接實現輪播圖的視圖控件。因此我們需要通過組合視圖控件的方法去實現輪播。

首先分析輪播圖的結構組成,從靜止上看,輪播圖就是在一個橫向的滾動視圖上添加了幾張圖片,然后在滾動視圖的底部添加一個頁碼控制器來監聽滾動視圖顯示的是第幾張圖片,接下來的循環滾動,只需要添加一個定時器來讓滾動視圖有序地進行輪回滾動。

考慮到視圖的復用性和點擊觸發事件,我們使用 UICollectionView 作為主控件,設置翻頁的橫向滾動,在 UICollectionViewCell 上添加和 UICollectionView 一樣大小的 UIImageView。為了讓封裝之后的輪播圖類方便在視圖控制器上的使用,將這個類繼承于 UIViewUICollectionView 和頁碼控制器 UIPageControl 的布局將在類的初始化實現。為了能夠讓輪播圖的點擊事件得到響應,在初始化的時候,傳入一個可以處理用戶點擊了第幾張輪播圖片的 block

不多說了,直接上代碼。
接口頭文件 CJMRotationPictureController.h

/**
選中圖片完成處理

@param nPicture 選中的第幾張圖片
*/
typedef void(^ selectCompletion)(NSInteger nPicture);


/**
輪播圖
*/
@interface CJMRotationPictureController : UIView


/**
初始化方法

@param frame 布局
@param complete 選擇處理
@return 實例化對象
*/
- (instancetype)initWithFrame:(CGRect)frame selectComplete:(selectCompletion)complete;

/**
更新輪播圖,支持 UIImage 數組 或 圖片地址 NSString 數組

@param arrPicture 圖片數據
*/
- (void)updateDataWithPictureArray:(NSArray *)arrPicture;

@end

實現文件 CJMRotationPictureController.m

// 主視圖的長寬
#define kViewWidth self.frame.size.width
#define kViewHeight self.frame.size.height

static NSString *gPictureID = @"PictureID";

@interface CJMRotationPictureController () <UICollectionViewDelegate, UICollectionViewDataSource>

/**
 主集合圖
 */
@property (nonatomic, weak) UICollectionView *collectMain;

/**
 頁碼控制器
 */
@property (nonatomic, weak) UIPageControl *pageShow;

/**
 數據源 UIImage 數組 或 圖片地址 NSString 數組
 */
@property (nonatomic, strong) NSArray *arrDataSource;

/**
 滾動計時器
 */
@property (nonatomic, strong) NSTimer *timerScroll;

/**
 事件處理
 */
@property (nonatomic, copy) selectCompletion blockComplete;

@end


@implementation CJMRotationPictureController


/**
 初始化方法
 
 @param frame 布局
 @param complete 選擇處理
 @return 實例化對象
 */
- (instancetype)initWithFrame:(CGRect)frame selectComplete:(selectCompletion)complete {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        [self initLayout];
        self.blockComplete = complete;
    }
    return self;
}

- (void)initLayout {
    
    [self setBackgroundColor:[UIColor whiteColor]];
    
    
    // 主集合圖
    // 自適應布局
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setMinimumLineSpacing:0];
    [flowLayout setMinimumInteritemSpacing:0];
    // 水平方向滾動
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [flowLayout setItemSize:self.frame.size];
    
    UICollectionView *collectTemp = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kViewWidth, kViewHeight) collectionViewLayout:flowLayout];
    [collectTemp setBackgroundColor:[UIColor whiteColor]];
    // 隱藏水平滾動條
    collectTemp.showsHorizontalScrollIndicator = NO;
    // 翻頁效果
    collectTemp.pagingEnabled = YES;
    collectTemp.delegate = self;
    collectTemp.dataSource = self;
    [self addSubview:collectTemp];
    self.collectMain = collectTemp;
    // 注冊cell
    [self.collectMain registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:gPictureID];
    
    
    // 頁碼控制器
    UIPageControl *pageTemp = [[UIPageControl alloc] initWithFrame:CGRectMake(kViewWidth * 0.8, kViewHeight - 30, kViewWidth/5, 30)];
    // 只有一頁是隱藏
    [pageTemp setHidesForSinglePage:YES];
    // 普通顏色
    [pageTemp setPageIndicatorTintColor:[UIColor colorWithWhite:1.0 alpha:0.5]];
    // 當前頁顏色
    [pageTemp setCurrentPageIndicatorTintColor:[UIColor colorWithWhite:1.0 alpha:0.8]];
    [self addSubview:pageTemp];
    self.pageShow = pageTemp;
    
    self.arrDataSource = [NSArray array];
}


#pragma mark - UICollectionViewDataSourse 收集數據源處理
// 區域數
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

// 單元數
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return [self.arrDataSource count];
}

// cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:gPictureID forIndexPath:indexPath];
    
    // 圖片
    UIImageView *imgvPicture = (UIImageView *)[cell viewWithTag:10];
    if (imgvPicture == nil) {
        
        // 添加子控件
        imgvPicture = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kViewWidth, kViewHeight)];
        [imgvPicture setTag:10];
        [imgvPicture setClipsToBounds:YES];
        [imgvPicture setContentMode:UIViewContentModeScaleAspectFill];
        [cell addSubview:imgvPicture];
    }
    
    // 數組對象的類型
    if ([self.arrDataSource[indexPath.row] isKindOfClass:[UIImage class]]) {
        
        // UIImage
        [imgvPicture setImage:self.arrDataSource[indexPath.row]];
        
    } else if ([self.arrDataSource[indexPath.row] isKindOfClass:[NSString class]]) {
        
        // 圖片地址的 NSString
        NSURL *urlImage = [NSURL URLWithString:self.arrDataSource[indexPath.row]];
        NSData *dataImage = [NSData dataWithContentsOfURL:urlImage];
        if (dataImage) {
            
            [imgvPicture setImage:[UIImage imageWithData:dataImage]];
        }
    }
    
    return cell;
}

// 選中項處理
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 通過委托傳遞選中序號
    self.blockComplete(indexPath.row);
}


#pragma mark - 對外接口
/**
 更新輪播圖,支持 UIImage 數組 或 圖片地址 NSString 數組
 
 @param arrPicture 圖片數據
 */
- (void)updateDataWithPictureArray:(NSArray *)arrPicture {
    
    self.arrDataSource = arrPicture;
    // 頁視圖布局
    CGFloat fwidth = 13 * [self.arrDataSource count];
    [self.pageShow setFrame:CGRectMake(kViewWidth - 14 - fwidth, kViewHeight - 30, fwidth, 30)];
    // 總頁數
    [self.pageShow setNumberOfPages:[self.arrDataSource count]];
    // 當前頁
    [self.pageShow setCurrentPage:0];
    
    // 更新集合視圖
    [self.collectMain reloadData];
    
    // 信息不少于2條是,啟動計時器,否則停止計時器
    if ([self.arrDataSource count] > 2) {
        
        // 啟動定時器
        [self fireScollerTimer];
    } else {
        
        // 關閉定時器
        if (self.timerScroll) {
            
            [self.timerScroll invalidate];
        }
    }
    
}


/**
 啟動定時器
 */
- (void)fireScollerTimer {
    
    if (self.timerScroll == nil) {
        
        self.timerScroll = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(timerActionWithTimer:) userInfo:nil repeats:YES];
    }
    [[NSRunLoop currentRunLoop] addTimer:self.timerScroll forMode:NSRunLoopCommonModes];
}


/**
 定時器事件
 
 @param timer 定時器
 */
- (void)timerActionWithTimer:(NSTimer* )timer {
    
    // 通過改變滾動的滾動位置來達到切換的效果
    // 獲取當前的所處的滾動位置
    float offset_x = self.collectMain.contentOffset.x;
    // 每次滾動一條
    offset_x += kViewWidth;
    
    // 滾屏寬度
    CGFloat scrollWidth = ([self.arrDataSource count] - 1) * kViewWidth;
    
    // 最后一條之后,回到第一條
    if (offset_x > scrollWidth) {
        
        // 最后的偏移量
        [self.collectMain setContentOffset:CGPointMake(0, 0) animated:NO];
    } else {
        
        [self.collectMain setContentOffset:CGPointMake(offset_x, 0) animated:YES];
    }
    
}

/**
 更新頁碼
 */
- (void)updataPageNumber {
    
    float offset_x = self.collectMain.contentOffset.x;
    [self.pageShow setCurrentPage:offset_x/kViewWidth];
}


#pragma mark - UIScrollViewDelegate 滾動監聽
// 滾動視圖開始被拖動
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    // 定時器休眠
    [self.timerScroll setFireDate:[NSDate distantFuture]];
}

// 滾動視圖靜止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // 定時器 2 秒后重啟
    [self.timerScroll setFireDate:[NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]]];
}

// 滾動后--更新所滑到的頁碼
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    // 更新頁碼
    [self updataPageNumber];
}

@end

在視圖控制器上的調用:

CJMRotationPictureController *rotation = [[CJMRotationPictureController alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenWidth/2) selectComplete:^(NSInteger nPicture) {
       
        NSLog(@"點擊了第%ld圖片", nPicture);
}];
[self.view addSubview:rotation];
    
// 載入圖片
[rotation updateDataWithPictureArray:@[[UIImage imageNamed:@"desk1"], [UIImage imageNamed:@"test2"], [UIImage imageNamed:@"desk1"], [UIImage imageNamed:@"test2"]]];

結果截圖:


輪播圖

GitHub 上的代碼
使用 CocoaPods 集成:

pod 'CJMRotationPicture'
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,702評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,615評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,606評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,044評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,826評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,227評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,307評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,447評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,992評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,807評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,001評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,550評論 5 361
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,243評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,667評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,930評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,709評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,996評論 2 374

推薦閱讀更多精彩內容