您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

用 Objective-C 實現無限循環輪播器

編輯:iOS 相關教學

先看完成後的效果:

無限輪播的核心思路是:只放三個 UIImageView,永遠讓中間那張顯示當前頁,滑到兩側時立刻無動畫地把 contentOffset 拉回中央。這樣一來,無論使用者滑多少次都不會碰到滾動邊界,也就實現了「無限」的錯覺。

一、控制器中的呼叫方式

#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;

#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];
}

/** 用程式碼建立時呼叫 */
- (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];

        // 只建立三個 imageView
        for (int i = 0; i < ImageViewCount; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.contentMode = self.imageViewcontentMode;
            [scrollView addSubview:imageView];
        }
    }
    return self;
}

/** 布局子控件 */
- (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 {
    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];
}

五、計時器與便捷建構方法

#pragma mark - 計時器處理

- (void)startTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(next:)
                                                    userInfo:nil
                                                     repeats:YES];
    // 加入 Run Loop 的 CommonModes,避免滾動時計時器被暫停
    [[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];
    }
}

+ (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

幾個實作上容易踩到的細節:

  • contentOffset 復位時千萬不能帶動畫,否則使用者會看到畫面「倒帶」。
  • 計時器一定要加入 NSRunLoopCommonModes,否則在滾動過程中會被暫停,導致自動播放看起來失靈。
  • 建議在檢視消失或離開時呼叫 stopTimer,避免計時器持有 self 造成記憶體洩漏。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved