您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Objective-C 手寫無限循環輪播器(支持橫向與縱向)

編輯:iOS 開發綜合

無限輪播的核心難點只有一個:只有三個 UIImageView,卻要顯示無限張圖。做法是在每次滾動停下來後,把偏移量無聲地拉回中間那一格,同時更新三張圖的內容,讓用戶察覺不到「重置」的瞬間。本文給出完整實現。

效果預覽

一、控制器中的調用

#import "ViewController.h"
#import "SNInfiniteScrollView.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableArray *images = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        NSString *imageName = [NSString stringWithFormat:@"ad_%02d", i];
        UIImage  *image     = [UIImage imageNamed:imageName];
        [images addObject:image];
    }

    UIView *scrollView = [SNInfiniteScrollView scrollViewWithFrame:CGRectMake(0, 20, 414, 200)
                                                        superView:self.view
                                                           images:images
                                                  scrollDirection:ScrollDirectionHorizontal
                                            pageIndicatorTintColor:[UIColor lightGrayColor]
                                      currentPageIndicatorTintColor:[UIColor orangeColor]
                                                 imageViewcontentMode:UIViewContentModeScaleAspectFit];
    [self.view addSubview:scrollView];
}

@end

二、輪播視圖的核心實現

#import "SNInfiniteScrollView.h"

static int const ImageViewCount = 3;   // 只復用三個 imageView

#define scrollViewWidth  self.scrollView.frame.size.width
#define scrollViewHeight self.scrollView.frame.size.height

@interface SNInfiniteScrollView () <UIScrollViewDelegate>
@property (weak, nonatomic) UIScrollView *scrollView;
@property (weak, nonatomic) NSTimer      *timer;
@property (nonatomic, assign) NSInteger pageIndex;   // 當前頁
@end

@implementation SNInfiniteScrollView

- (void)setImages:(NSArray<UIImage *> *)images
{
    _images = images;
    self.pageIndex = 0;
    [self updateContent];
    [self startTimer];
}

#pragma mark - 初始化

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        self.scrollView = scrollView;
        scrollView.delegate = self;
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator   = NO;
        scrollView.pagingEnabled = YES;
        scrollView.bounces       = NO;
        [self addSubview:scrollView];

        for (int i = 0; i < ImageViewCount; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.contentMode = self.imageViewcontentMode;   // 避免圖片變形
            [scrollView addSubview:imageView];
        }
    }
    return self;
}

#pragma mark - 佈局

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;

    if (self.scrollDirection == ScrollDirectionVertical) {
        self.scrollView.contentSize = CGSizeMake(0, ImageViewCount * self.bounds.size.height);
    } else {
        self.scrollView.contentSize = CGSizeMake(ImageViewCount * self.bounds.size.width, 0);
    }

    for (int i = 0; i < ImageViewCount; i++) {
        UIImageView *imageView = self.scrollView.subviews[i];
        if (self.scrollDirection == ScrollDirectionVertical) {
            imageView.frame = CGRectMake(0,
                                         i * self.scrollView.frame.size.height,
                                         self.scrollView.frame.size.width,
                                         self.scrollView.frame.size.height);
        } else {
            imageView.frame = CGRectMake(i * self.scrollView.frame.size.width,
                                         0,
                                         self.scrollView.frame.size.width,
                                         self.scrollView.frame.size.height);
        }
    }

    [self updateContent];
}

#pragma mark - 內容更新(無限循環的關鍵)

- (void)updateContent
{
    // 依序把「上一張 / 當前 / 下一張」分配給三個 imageView
    for (int i = 0; i < self.scrollView.subviews.count; i++) {
        NSInteger pageIndex = self.pageIndex;
        UIImageView *imageView = self.scrollView.subviews[i];

        if (i == 0) {
            pageIndex--;         // 最左(上)一格放上一張
        } else if (i == 2) {
            pageIndex++;         // 最右(下)一格放下一張
        }

        // 兩端做環形緩衝,實現首尾相接
        if (pageIndex < 0) {
            pageIndex = self.images.count - 1;
        } else if (pageIndex >= self.images.count) {
            pageIndex = 0;
        }

        imageView.tag   = pageIndex;             // 用 tag 記錄這是第幾張
        imageView.image = self.images[imageView.tag];
    }

    // 無聲地回到中間那一格;注意不能帶動畫
    if (self.scrollDirection == ScrollDirectionVertical) {
        self.scrollView.contentOffset = CGPointMake(0, scrollViewHeight);
    } else {
        self.scrollView.contentOffset = CGPointMake(scrollViewWidth, 0);
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 找出此刻正好停在窗口中央的那個 imageView
    NSInteger page = self.pageIndex;
    CGPoint point = CGPointZero;

    for (int i = 0; i < self.scrollView.subviews.count; i++) {
        UIImageView *imageView = self.scrollView.subviews[i];
        point = [scrollView convertPoint:imageView.frame.origin toView:self.superview];

        if (self.scrollDirection == ScrollDirectionVertical) {
            if (ABS(point.y - self.frame.origin.y) < 1.0) {
                page = imageView.tag;
            }
        } else {
            if (ABS(point.x - self.frame.origin.x) < 1.0) {
                page = imageView.tag;
            }
        }
    }

    self.pageIndex = page;
    self.pageControl.currentPage = page;

    [self updateContent];   // 拖動結束即歸位
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];       // 用戶開始操作,暫停自動播放
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];      // 手放開就恢復自動播放
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self updateContent];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self updateContent];   // 兜底:確保動畫式改 offset 後也能歸位
}

#pragma mark - 定時器

- (void)startTimer
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                     target:self
                                                  selector:@selector(next:)
                                                  userInfo:nil
                                                   repeats:YES];
    // 加入 CommonModes,否則在滾動 tracking 狀態下定時器會被暫停
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)next:(NSTimer *)timer
{
    if (self.scrollDirection == ScrollDirectionVertical) {
        [self.scrollView setContentOffset:CGPointMake(0, 2 * self.scrollView.frame.size.height)
                                 animated:YES];
    } else {
        [self.scrollView setContentOffset:CGPointMake(2 * self.scrollView.frame.size.width, 0)
                                 animated:YES];
    }
}

#pragma mark - 便捷構造方法

+ (instancetype)scrollViewWithFrame:(CGRect)frame
                          superView:(UIView *)superView
                             images:(NSArray<UIImage *> *)images
                    scrollDirection:(ScrollDirection)scrollDirection
               pageIndicatorTintColor:(UIColor *)pageIndicatorTintColor
         currentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor
                    imageViewcontentMode:(UIViewContentMode)imageViewcontentMode
{
    SNInfiniteScrollView *scrollView = [[SNInfiniteScrollView alloc] init];
    scrollView.frame = frame;
    scrollView.imageViewcontentMode = imageViewcontentMode;
    scrollView.scrollDirection      = scrollDirection;
    scrollView.images               = images;

    UIPageControl *pageControl = [[UIPageControl alloc] init];
    scrollView.pageControl = pageControl;
    pageControl.enabled = NO;   // 禁止用戶直接點擊翻頁
    pageControl.currentPageIndicatorTintColor = currentPageIndicatorTintColor;
    pageControl.pageIndicatorTintColor        = pageIndicatorTintColor;
    pageControl.numberOfPages = scrollView.images.count;
    pageControl.bounds = CGRectMake(0, 0, scrollView.bounds.size.width, 44);
    pageControl.center = CGPointMake(scrollView.bounds.size.width * 0.5,
                                     scrollView.bounds.size.height * 0.9);
    [scrollView addSubview:pageControl];

    [superView addSubview:scrollView];
    return scrollView;
}

@end

三、原理總結

整套邏輯可以濃縮成三句話:

  1. 三格輪轉:scrollView 裡永遠只有三個 imageView,分別承載「上一張、當前、下一張」。索引越界時用取模思想做環形緩衝,首尾自然相接。
  2. 無聲歸位:每次滾動停下,立刻把 contentOffset 拉回中間格(注意必須 animated:NO)。由於中間格內容已被 updateContent 換成最新的「當前頁」,用戶視覺上毫無跳變。
  3. 定時輪播:用 NSTimer 週期性地把 offset 推到第三格並帶動畫;動畫結束後 scrollViewDidEndScrollingAnimation: 觸發歸位,形成閉環。

兩個容易忽略的細節:一是 NSTimer 一定要加入 NSRunLoopCommonModes,否則用戶拖動期間(tracking 模式)定時器會停止,體驗上就是「一碰就停了」;二是 updateContent 中改 contentOffset 絕不能帶動畫,否則會看到明顯的回彈跳動。

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