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

用 UIScrollView 打造 iOS 輪播圖的完整實作教學

編輯:iOS 開發綜合

輪播圖幾乎是每個 App 首頁的標配。它的本質並不神秘:一個開啟分頁能力的 UIScrollView 負責承載橫向排列的圖片,一個 UIPageControl 負責顯示當前頁碼,再加一個 NSTimer 負責自動翻頁,三者協作就足夠了。

整體思路

把每張圖片以「螢幕寬度」為單位依次向右排開,讓 contentSize 的寬度等於圖片數量乘以螢幕寬度。開啟 pagingEnabled 之後,使用者手指一掃便會自動吸附到整頁,省去自行計算偏移量的麻煩。頁碼同步則藉由 scrollViewDidScroll: 回呼,用目前的 contentOffset.x 反推頁碼即可。

程式碼實作

#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
#define KImageCount 3
#define KImage_Height 250

@interface ViewController () <UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation ViewController

- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, KImage_Height)];
        _scrollView.pagingEnabled = YES;                    // 整頁吸附
        _scrollView.showsHorizontalScrollIndicator = NO;    // 隱藏橫向捲軸
    }
    return _scrollView;
}

- (UIPageControl *)pageControl {
    if (_pageControl == nil) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.scrollView.frame.size.height - 30, SCREEN_SIZE.width, 20)];
        _pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:65/255.0 green:168/255.0 blue:100/255.0 alpha:1.0];
        _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    }
    return _pageControl;
}

- (void)setupUI {
    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.pageControl];

    CGFloat imageW = SCREEN_SIZE.width;
    CGFloat imageH = KImage_Height;

    for (int i = 0; i < KImageCount; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * imageW, 0, imageW, imageH)];
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", i + 1]];
        [self.scrollView addSubview:imageView];
    }

    // 關鍵:contentSize 必須等於所有圖片寬度總和
    self.scrollView.contentSize = CGSizeMake(KImageCount * imageW, 0);
    self.scrollView.delegate = self;
    self.pageControl.numberOfPages = KImageCount;

    [self addTimer];
}

#pragma mark - 自動輪播

- (void)addTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

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

- (void)nextImage {
    int i = (int)self.pageControl.currentPage;
    if (i == KImageCount - 1) {
        i = -1;     // 回到起點,形成循環
    }
    i++;
    [self.scrollView setContentOffset:CGPointMake(i * self.scrollView.frame.size.width, 0) animated:YES];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self turnOffTimer];        // 手指一碰就暫停,避免搶畫面
}

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

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.pageControl.currentPage = (self.scrollView.frame.size.width * 0.5 + self.scrollView.contentOffset.x) / self.scrollView.frame.size.width;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"輪播圖";
    [self setupUI];
}

@end

幾個容易踩到的細節

1. 拖曳時務必暫停計時器

若不監聽 scrollViewWillBeginDragging:,計時器會在使用者滑動途中把畫面硬拉回下一頁,操作手感立刻變差。對應的作法是開始拖曳時 invalidate,結束拖曳後重建計時器。

2. 記得加入 RunLoop 並慎選 Mode

scheduledTimerWithTimeInterval: 建立出來的計時器會自動加入當前 RunLoop,但若使用手動建立的方式,就必須自己 addTimer:forMode:。當捲動是伴隨慣性(例如 UITextView 內的追蹤模式)時,若只加入預設模式,計時器在滑動期間會停止觸發,這時可考慮改用 NSRunLoopCommonModes。

3. 別忘了在 dealloc 之外的地方回收計時器

當 repeats 設為 YES 時,計時器會強引用 target,導致 dealloc 永遠不被呼叫。實務上可在 viewDidDisappear: 中統一關閉,並在 viewDidAppear: 重新啟動。

4. 想做到無限循環?

本文的做法是「播到最後一頁就跳回第一頁」,視覺上會有一次快速倒捲。若要真正無縫,通常會在頭尾各複製一張圖(第一張的副本放最後、最後一張的副本放最前),並在 scrollViewDidEndDecelerating: 中偵測是否停在副本頁,若是則不帶動畫地瞬移到真實頁面。

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