您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

SLRoateView:一個可複用的輪播圖組件實現

編輯:iOS 技巧大全
[摘要]本文分享一個基於 UIScrollView 實現的輪播圖組件 SLRoateView,支持無限循環、定時自動輪播、手勢拖拽與點擊回調,並附完整實現代碼。

下面是一個封裝好的輪播圖組件。核心思路是永遠只使用三個 UIImageView(左、中、右),通過在滾動結束後重新加載圖片並把 contentOffset 重置回中間位置,从而实现「無限循環」的視覺效果。

頭文件

#import <UIKit/UIKit.h>

typedef void(^Click)(NSInteger index);

@interface SLRoateView : UIView

/*
   關於 cell 復用:
   tableView 的 cell 復用機制在這種場景下意義不大。
   因為無論如何都要預先準備好圖片數組,用多個 tableView 反而增加複雜度。
   因此這裡只支持放置 imageView。

   如果未來要支持在 scrollView 上裝載別的 View(例如某些 App 首頁那樣,
   用 scrollView 承載多個 tableView 做分類展示,愛奇藝首頁的電影、電視、
   綜藝、動漫就是這種形式),那就不適合再有輪播和點擊屬性了:
   // 是否允許輪播,默認允許;設置為 NO 則不自動滾動
   // @property(nonatomic, assign) BOOL AllowCarousel;
   // 是否支持點擊,只需判斷 block 是否為空,為空則不添加手勢
   // @property(nonatomic, assign) BOOL SupportInteraction;
*/

// 創建
+ (SLRoateView *)roateViewWithFrame:(CGRect)frame
                              array:(NSArray *)array
                              click:(Click)click;

@end

實現文件

#import "SLRoateView.h"

@interface SLRoateView () <UIScrollViewDelegate>

@property (nonatomic, strong) NSArray *array;
@property (nonatomic, copy)   Click click;

@property (nonatomic, assign) CGFloat KRoateWidth;
@property (nonatomic, assign) CGFloat KRoateHeight;

@property (nonatomic, strong) UIImageView *leftImageView;
@property (nonatomic, strong) UIImageView *centerImageView;
@property (nonatomic, strong) UIImageView *rightImageView;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIScrollView *scroll;

@end

@implementation SLRoateView

+ (SLRoateView *)roateViewWithFrame:(CGRect)frame
                              array:(NSArray *)array
                              click:(Click)click {
    SLRoateView *roateView = [[SLRoateView alloc] initWithFrame:frame
                                                        array:array
                                                        click:click];
    return roateView;
}

- (instancetype)initWithFrame:(CGRect)frame
                        array:(NSArray *)array
                        click:(Click)click {
    self = [super initWithFrame:frame];
    if (self) {
        self.KRoateWidth  = frame.size.width;
        self.KRoateHeight = frame.size.height;
        self.array = array;
        self.click = click;

        // scrollView 設置:contentSize 為三倍寬度,初始定位到中間那一屏
        self.scroll = [[UIScrollView alloc] initWithFrame:
                       CGRectMake(0, 0, _KRoateWidth, _KRoateHeight)];
        self.scroll.contentSize = CGSizeMake(_KRoateWidth * 3, 0);
        self.scroll.pagingEnabled = YES;
        self.scroll.contentOffset = CGPointMake(_KRoateWidth, 0);
        self.scroll.alwaysBounceVertical = NO;
        self.scroll.showsVerticalScrollIndicator = NO;
        self.scroll.alwaysBounceHorizontal = YES;
        self.scroll.showsHorizontalScrollIndicator = NO;
        self.scroll.delegate = self;
        [self addSubview:_scroll];

        [self addGestureRecognizer];
        [self addImageViews];
        [self setDefautImage];
        [self addPageControl];
        [self addTimer];
    }
    return self;
}

#pragma mark - 添加計時器

- (void)addTimer {
    // 在子線程中創建計時器,才能讓圖片輪播不受主線程其他任務影響
    // 關鍵:必須把 timer 加到的 RunLoop 中,並 run 起來,否則計時器不會觸發
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _timer = [NSTimer timerWithTimeInterval:3
                                        target:self
                                      selector:@selector(rotaView)
                                      userInfo:nil
                                       repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
        [[NSRunLoop currentRunLoop] run];
    });
}

- (void)rotaView {
    // 動畫從中間滾動到第三屏
    [_scroll setContentOffset:CGPointMake(_KRoateWidth * 2, 0) animated:YES];

    // 設置分頁:由於動畫是從中間移到第三張,
    // 所以 pageControl 要顯示的不是中間圖片,而是第三張
    _pageControl.currentPage = (_index + 1) % _array.count;

    if (_scroll.contentOffset.x / _KRoateWidth == 2) {
        [self reloadImage];
        // scrollView 無動畫回到中間
        [self.scroll setContentOffset:CGPointMake(_KRoateWidth, 0) animated:NO];
    }
}

#pragma mark - 添加點擊事件

- (void)addGestureRecognizer {
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc]
                                initWithTarget:self
                                        action:@selector(tapGestureRecognizer)]];
}

- (void)tapGestureRecognizer {
    if (_click) {
        _click(_pageControl.currentPage);
    }
}

#pragma mark - 添加圖片控件

- (void)addImageViews {
    _leftImageView = [[UIImageView alloc] initWithFrame:
                      CGRectMake(0, 0, _KRoateWidth, _KRoateHeight)];
    [self.scroll addSubview:_leftImageView];

    _centerImageView = [[UIImageView alloc] initWithFrame:
                        CGRectMake(_KRoateWidth, 0, _KRoateWidth, _KRoateHeight)];
    [self.scroll addSubview:_centerImageView];

    _rightImageView = [[UIImageView alloc] initWithFrame:
                       CGRectMake(_KRoateWidth * 2, 0, _KRoateWidth, _KRoateHeight)];
    [self.scroll addSubview:_rightImageView];
}

#pragma mark - 設置默認顯示圖片

- (void)setDefautImage {
    _leftImageView.image   = _array[_array.count - 1];
    _centerImageView.image = _array[0];
    _rightImageView.image  = _array[1];

    _index = 0;
    _pageControl.currentPage = _index;
}

#pragma mark - 添加分頁控件

- (void)addPageControl {
    // 注意:sizeForNumberOfPages: 是類方法,
    // 需要先有一個實例才能借用它的尺寸計算能力,因此先 alloc 再設置 frame
    _pageControl = [[UIPageControl alloc] init];
    CGSize size = [_pageControl sizeForNumberOfPages:_array.count];
    _pageControl.frame = CGRectMake(0, 0, size.width, size.height);
    _pageControl.center = CGPointMake(_KRoateWidth / 2, _KRoateHeight - size.height / 2);
    _pageControl.numberOfPages = _array.count;
    [self addSubview:_pageControl];
}

#pragma mark - 滾動停止事件

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 5 秒後恢復自動輪播
    [_timer performSelector:@selector(setFireDate:)
                 withObject:[NSDate distantPast]
                 afterDelay:5];

    [self reloadImage];

    // scrollView 回到中間位置
    [self.scroll setContentOffset:CGPointMake(_KRoateWidth, 0) animated:NO];

    // 設置分頁
    _pageControl.currentPage = _index;
}

#pragma mark - 重新加載圖片

- (void)reloadImage {
    NSInteger leftIndex, rigtIndex;
    CGPoint offset = self.scroll.contentOffset;

    // 根據停止位置判斷是向前還是向後翻頁
    if (offset.x > _KRoateWidth) {
        _index = (_index + 1) % _array.count;
    } else if (offset.x < _KRoateWidth) {
        _index = (_index + _array.count - 1) % _array.count;
    }

    _centerImageView.image = _array[_index];

    leftIndex = (_index + _array.count - 1) % _array.count;
    rigtIndex = (_index + 1) % _array.count;

    _leftImageView.image  = _array[leftIndex];
    _rightImageView.image = _array[rigtIndex];
}

#pragma mark - 開始拖拽

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView.isDragging) {
        // 取消之前掛起的恢復請求,並暫停計時器,避免與手勢衝突
        [NSObject cancelPreviousPerformRequestsWithTarget:_timer];
        [_timer setFireDate:[NSDate distantFuture]];
    }
}

@end

實現要點說明

1. 為什麼用三個 imageView?
無論圖片有多少張,屏幕上同時可見的最多只有三屏(上一張、當前、下一張)。只維護這三個 imageView,內存佔用恆定,也就天然實現了「復用」,不必像 UICollectionView 那樣引入緩存池的複雜度。

2. 無限循環的關鍵
contentOffset 永遠在滾動結束後被無動畫地重置回中間那一屏,用戶感知不到跳變,视觉上就是無限循環。

3. 計時器的坑
NSTimer 必須被添加到 RunLoop 並 run 起來才會觸發,這是新手最常忽略的一步。另外,計時器對 target 是強引用,如果 target 是當前控制器,會導致 dealloc 不被調用。工程化時建議改用 scheduledTimerWithTimeInterval:repeats:block:(iOS 10+)或引入一個中間 proxy 對象來打破循環引用,並在合適的時機調用 invalidate。

4. 手勢與自動播放的衝突
用戶開始拖拽時必須暫停計時器,滾動停止後再延遲恢復,否則會出現「手動滑到一半被自動動畫搶走」的尷尬情況。

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