Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

iOS 開發:用 UIScrollView 實作圖片自動輪播

編輯:關於 Android 程式設計

以下示範一個類似 Android 圖片庫的輪播效果:圖片每隔一段時間自動切換,使用者也可以手動滑動,滑動期間暫停自動播放,放手後恢復。

完整實作

#import "ViewController.h"

#define ImageViewCount 5

@interface ViewController () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *imageViewPageControl;
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self addImageView2ScrollView];

    self.imageScrollView.contentSize =
            CGSizeMake(self.imageScrollView.frame.size.width * ImageViewCount, 0);
    self.imageScrollView.delegate = self;
    self.imageScrollView.pagingEnabled = YES;   // 讓滑動以整頁為單位吸附
    self.imageViewPageControl.numberOfPages = ImageViewCount;

    [self addScrollTimer];
}

/** 自動切換到下一張 */
- (void)rotatePic {
    NSInteger currentPageIndex = self.imageViewPageControl.currentPage;
    if (++currentPageIndex == ImageViewCount) {
        currentPageIndex = 0;
    }
    CGFloat offsetX = currentPageIndex * self.imageScrollView.frame.size.width;
    [UIView animateWithDuration:1 animations:^{
        self.imageScrollView.contentOffset = CGPointMake(offsetX, 0);
    }];
}

/** 把圖片鋪進 ScrollView */
- (void)addImageView2ScrollView {
    CGFloat imageWidth = self.imageScrollView.frame.size.width;
    CGFloat imageHeight = self.imageScrollView.frame.size.height;

    for (int i = 0; i < ImageViewCount; i++) {
        UIImageView *imageInScroll = [[UIImageView alloc] init];
        imageInScroll.frame = CGRectMake(i * imageWidth, 0, imageWidth, imageHeight);
        imageInScroll.image = [UIImage imageNamed:
                [NSString stringWithFormat:@"img_%02d", i + 1]];
        [self.imageScrollView addSubview:imageInScroll];
    }
}

/** 滑動過程中同步頁碼指示器 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offX = scrollView.contentOffset.x;
    NSInteger currentPageIndex =
            (offX + 0.5f * scrollView.frame.size.width) / scrollView.frame.size.width;
    self.imageViewPageControl.currentPage = currentPageIndex;
}

- (void)addScrollTimer {
    self.timer = [NSTimer timerWithTimeInterval:2
                                         target:self
                                       selector:@selector(rotatePic)
                                       userInfo:nil
                                        repeats:YES];
    // 加入 RunLoop 的 CommonModes,滑動期間計時器才不會被延後
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

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

/** 開始拖動時暫停自動播放 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeScrollTimer];
}

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

@end

幾個關鍵細節

UIScrollView 部分

  • contentSize 必須正確設定。它決定可滑動的內容範圍,這裡用「單頁寬度 × 頁數」讓五張圖片水平排列。
  • delegate 必須設定,否則 scrollViewDidScroll: 等回呼不會被觸發,頁碼指示器就無法同步。
  • pagingEnabled 讓每次滑動自動吸附到最近的整頁位置,是輪播手感的關鍵。

NSTimer 部分

  • 必須加入 RunLoop 才會啟動。timerWithTimeInterval: 只是建立物件,要透過 addTimer:forMode: 掛上執行緒的 RunLoop 才會真正計時。
  • mode 的選擇很重要。若用預設的 NSDefaultRunLoopMode,使用者在滑動時計時器會被暫停(因為此時 RunLoop 處於 tracking 模式),畫面會出現「滑完才又開始跳」的頓感。改用 NSRunLoopCommonModes 可讓計時在滑動期間持續。
  • 務必 invalidate 回收。NSTimer 會強引用 target,未 invalidate 會導致 ViewController 無法釋放。除了上述的拖動處理,也應在 dealloc 或 viewDidDisappear 中確保清除。

可再優化的方向

目前的做法是把所有圖片一次性鋪進 ScrollView,頁數多時記憶體吃緊。若要支援大量圖片,建議改為「只保留前後各一頁」的複用策略,或直接使用 UICollectionView 搭配 isPagingEnabled,讓系統自動回收離開畫面的 cell。 timer 也可換成 CADisplayLink,它能與畫面刷新同步,在動畫場景下更平順。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved