您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 自動無限輪播器實現:定時器 + 雙 Cell 輪轉方案

編輯:iOS 程式設計技術
  • 相比之前發布的手動版本,這次做了升級,加入自動輪播能力,特別適合放在團購類 App 的分類標題下方作為橫幅。

實現思路

  • 開啟一個定時器,把切換操作放進 RunLoop;每隔固定時間觸發一次。
  • 關鍵點:App 啟動後自動輪播;一旦用戶手動拖拽,先讓定時器停止;拖拽結束後再重新開啟一個定時器。

核心設計

  • 整個 collectionView 中只實際使用 2 個 cell,中間位置始終展示第二個 cell。
  • 滾動時,向前滾動後當前 cell 的 index 為 0,向後滾動後為 2。用當前 cell 的 index 減去 1,得到 +1 或 -1,從而不斷讓圖片索引加一或減一,實現圖片切換。
  • 聲明一個全局變量 index 保存圖片索引,用於切換當前 cell 上顯示的圖片。
  • 滾動之前,先讓顯示中的 cell 的 index 變成 1,這一步在 viewDidLoad 中完成。
  • 一次滾動結束後,再用代碼把當前 cell 設回第二個 cell(本質就是把 index 改回 1)。
  • 還有一個線程問題:連續快速滾動後停下,當前圖片會閃動,原因是異步並發導致線程不安全。解法是把「滾動結束後重置 cell」的代碼放到主隊列執行。

準備工作

創建 CollectionViewController,關聯 storyboard,完成類綁定、cell 綁定與可重用標識綁定。

cell.h 文件:

// PBCollectionCell.h
// 無限滾動
#import <UIKit/UIKit.h>

@interface PBCollectionCell : UICollectionViewCell
@property(nonatomic,strong) UIImage *img;
@end

cell.m 文件:

// PBCollectionCell.m
#import "PBCollectionCell.h"

@interface PBCollectionCell ()
//不要忘記給collectionView的cell上設置圖片框,並拖線到cell分類中
@property (strong, nonatomic) IBOutlet UIImageView *imgView;
@end

@implementation PBCollectionCell
//重寫img的set方法給cell賦值(調用cell.img = img時會回調setImg:)
-(void)setImg:(UIImage *)img{
    _img = img;
    self.imgView.image = img;
}
@end

控制器代碼詳解

// ViewController.m
#import "ViewController.h"
#import "PBCollectionCell.h"

//定義宏圖片的個數
#define kPictureCount 3

@interface ViewController ()
@property (strong, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
/** 圖片的索引 */
@property(nonatomic,assign) NSInteger index;
//聲明定時器屬性方便在不同方法中訪問
@property(nonatomic,weak) NSTimer *timer;
@end
  • 聲明定時器屬性,方便在不同方法之間訪問;
  • 聲明全局變量 index,用於在滾動過程中拼接要切換的圖片索引。
@implementation ViewController

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return kPictureCount;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * ID = @"cell";
    PBCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];

    //圖片索引只有下一張或者上一張,即+1或者-1,為了切換圖片
    //中間的cell的indexPath.item是1,滾動後變成2或者0
    //湊成next值為+1或者-1,讓圖片索引加1或減1來完成切換
    NSInteger next = indexPath.item - 1;
    //為了不讓next越界,進行取余運算
    next = (self.index + kPictureCount + next) % kPictureCount;

    NSString *imgName = [NSString stringWithFormat:@"%02ld", next + 1];
    UIImage *img = [UIImage imageNamed:imgName];
    cell.img = img;
    return cell;
}

在 viewDidLoad 中把當前顯示的 cell 設為第二個 cell。此後向前滾動時 index 減 1(此時 indexPath.item 為 0),向後滾動時 index 加 1(此時 indexPath.item 為 2)。

那圖片索引到底怎麼拼?靠的就是全局變量 self.index:

  • cell 向前滾動時,圖片索引為 self.index - 1,此時 indexPath.item 為 0,圖片索引確實需要減 1;
  • cell 向後滾動時,圖片索引為 self.index + 1,此時 indexPath.item 為 2,圖片索引確實需要加 1;
  • 結論:用 indexPath.item - 1 再加上 self.index,就能算出下一個即將入場的 cell 該顯示哪張圖。
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //計算偏移的整數倍,偏移了0或者是2
    //-1是讓self.index圖片索引+1 或者 -1以切換圖片
    NSInteger offset = scrollView.contentOffset.x / scrollView.bounds.size.width - 1;
    self.index = (offset + self.index + kPictureCount) % kPictureCount;

    //本質就是改變cell的索引,再根據self.index來切換圖片
    //使用取余讓圖片索引不至於越界
    //異步主隊列執行,為了不讓連續滾動停止後圖片有閃動
    dispatch_async(dispatch_get_main_queue(), ^{
        [self scrollToSecondCell];
    });
}
  • cell 停止滾動後,把圖片索引 self.index 計算出來並保存到全局變量。這樣下次調用數據源方法返回 cell 時,就能通過 indexPath.item 的 +1/-1 疊加 self.index 正確切換圖片。
  • 滾動結束後把「重置 cell」的操作放進主隊列異步執行:這樣不會阻塞主線程,主隊列任務順序執行,等當前任務收尾後再把 cell 切回第二個,就不會出現連續滾動後閃圖的 bug。
//封裝設置當前顯示的cell為第二個cell的方法
-(void)scrollToSecondCell{
    NSIndexPath *idxPath = [NSIndexPath indexPathForItem:1 inSection:0];
    [self.collectionView scrollToItemAtIndexPath:idxPath
                              atScrollPosition:UICollectionViewScrollPositionLeft
                                      animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.flowLayout.itemSize = self.collectionView.bounds.size;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowLayout.minimumLineSpacing = 0;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;

    [self scrollToSecondCell];

    //開啟定時器使程序啟動就開始滾動
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self
                                                selector:@selector(nextPic)
                                                userInfo:nil
                                                 repeats:YES];
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    [runloop addTimer:self.timer forMode:NSRunLoopCommonModes];
}
@end
#pragma mark - 每隔一秒執行一次切換圖片
-(void)nextPic{
    CGFloat w = 2 * self.collectionView.bounds.size.width;
    [self.collectionView setContentOffset:CGPointMake(w, 0) animated:YES];
}
#pragma mark - 手動開始拖拽停止定時器
// 開始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    // 1. 停止計時器
    [self.timer invalidate];
}
#pragma mark - 停止拖拽開啟定時器
// 結束拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    // 重新開啟一個計時器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self
                                                selector:@selector(nextPic)
                                                userInfo:nil
                                                 repeats:YES];
    // 把self.timer加入RunLoop,並修改模式
    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    [runloop addTimer:self.timer forMode:NSRunLoopCommonModes];
}
  • 結束拖拽後重新開啟一個定時器。
  • 注意點:RunLoop 模式必須設為 NSRunLoopCommonModes,否則滾動過程中定時器會被暫停。
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    NSInteger offset = scrollView.contentOffset.x / scrollView.bounds.size.width;
    //第二個cell一直在中間所以,滾動停止後偏移倍數為0 或者 2
    offset = offset - 1;
    //cell的indexPath.item -1,即+1 或者 -1
    self.index = (kPictureCount + offset + self.index) % kPictureCount;

    //將操作放入主隊列異步執行,防止連續滾動停止後圖片錯位又變回正常顯示的圖片
    dispatch_async(dispatch_get_main_queue(), ^{
        [self scrollToSecondCell];
    });
}
  • 之所以要額外實現這個方法,是因為用代碼設置 contentOffset 觸發的滾動不會調用 scrollViewDidEndDecelerating:,也就無法完成 cell 的切換。
  • 而手動拖拽觸發的是 scrollViewDidEndDecelerating:。
  • 只有上述兩個方法中的任意一個被觸發,才能把中間顯示的 cell 重置為第二個 cell。

要點一

cell 滑動前、以及每次滑動結束後,都要用代碼把當前顯示的 cell 設為第二個 cell。在數據源的返回 cell 方法中,圖片切換靠的是 indexPath.item - 1(-1 或 +1)再加上圖片本身的索引 self.index,由此判斷即將滾出的 cell 該顯示上一張還是下一張。

要點二

cell 滾動結束後要計算當前顯示圖片的索引:用 contentOffset.x 除以 scrollView 寬度得出倍數並保存。之後再滑動時,數據源方法會用保存下來的 self.index 加上 indexPath.item - 1 來算出目標圖片索引。

要點三

注意 RunLoop 模式:代碼滾動偏移觸發的回調方法與手動拖拽觸發的方法並不相同,兩者都要處理。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved