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

iOS 照片瀏覽器實作:UIScrollView 分頁搭配 UIPageControl

編輯:關於 Android 程式設計

做一個左右滑動的照片瀏覽器,iOS 上最直白的組合是 UIScrollView 加 UIPageControl:前者負責承載橫向排列的圖片並提供分頁吸附,後者負責顯示「目前第幾張、共幾張」的頁點指示器。兩者透過 delegate 雙向同步。

AppDelegate 標頭

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, UIScrollViewDelegate>
{
    NSMutableArray *_mutArrImg;
    UIPageControl  *_pageControl;
    UIScrollView   *_scrollView;
}

@property (strong, nonatomic) UIWindow *window;

@end

實作

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    _scrollView = [[UIScrollView alloc] initWithFrame:self.window.bounds];
    [self.window addSubview:_scrollView];
    _scrollView.delegate = self;
    // 內容寬度 = 螢幕寬度 × 張數,讓四張圖橫向排開
    _scrollView.contentSize = CGSizeMake(320 * 4, self.window.frame.size.height);
    _scrollView.pagingEnabled = YES;   // 關鍵:讓滑動自動吸附到每一頁

    _mutArrImg = [NSMutableArray arrayWithCapacity:0];

    for (int i = 0; i < 4; i++) {
        NSURL *url = [NSURL URLWithString:
                @"https://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];

        dispatch_async(dispatch_get_global_queue(
                DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *imgData = [NSData dataWithContentsOfURL:url];
            UIImage *img = [UIImage imageWithData:imgData];

            // UI 操作必須回到主執行緒
            dispatch_sync(dispatch_get_main_queue(), ^{
                [_mutArrImg addObject:img];

                UIImageView *imgView = [[UIImageView alloc]
                        initWithFrame:CGRectMake(320 * i, 0, 320,
                                                 self.window.frame.size.height)];
                imgView.image = img;
                [_scrollView addSubview:imgView];
            });
        });
    }

    _pageControl = [[UIPageControl alloc]
            initWithFrame:CGRectMake(0, 400, 320, 30)];
    _pageControl.numberOfPages = 4;
    _pageControl.currentPage = 0;
    _pageControl.pageIndicatorTintColor = [UIColor redColor];
    [self.window addSubview:_pageControl];
    [_pageControl addTarget:self
                     action:@selector(actionCotrolPage:)
           forControlEvents:UIControlEventValueChanged];

    [self.window makeKeyAndVisible];
    return YES;
}

// 點頁點時,讓 scrollView 捲到對應位置
- (IBAction)actionCotrolPage:(id)sender
{
    [_scrollView setContentOffset:
            CGPointMake(_pageControl.currentPage * 320, 0) animated:YES];
}

// 使用者滑完一頁時,同步更新頁點
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageControl.currentPage = scrollView.contentOffset.x / 320;
}

@end

幾個值得改進的地方

硬寫 320 是個問題。範例把螢幕寬度寫死成 320,這是 iPhone 5 以前的尺寸。正確做法是取 [UIScreen mainScreen].bounds.size.width,並在 viewWillTransitionToSize: 中處理旋轉時的重新配置。更現代的方案是用 UIPageViewController,它會自動處理轉場動畫與尺寸變化。

dataWithContentsOfURL 是同步的。雖然範例已經把它丟到背景佇列,但這個 API 本身沒有任何逾時控制或快取機制,弱網環境下會卡很久。應該改用 NSURLSession 的 dataTask,並加上錯誤處理。

dispatch_sync 到主佇列有死鎖風險。若這段程式碼哪天被誤移到主執行緒執行,dispatch_sync 到同一個序列佇列會立即死鎖。改用 dispatch_async 更安全。

沒有處理圖片載入失敗。img 可能為 nil,此時 addObject 會加入一個 nil(在 NSMutableArray 中其實會直接崩潰,因為 nil 不能被加入)。應該先判斷再決定要不要 placeholder。

用 scrollViewDidEndDecelerating 同步頁點會漏案例。若使用者只是慢慢拖曳到一半就放手(沒有進入 decelerating),或透過程式設定 contentOffset,這個回呼不會觸發。較完整的做法是同時實作 scrollViewDidScroll: 並用 round(offset.x / width) 計算當前頁,再只在值變動時更新 pageControl。

最後補一個實務常忽略的細節:UIScrollView 裡的內容若有可能超出記憶體(例如幾十張高解析照片),應該改用 UICollectionView 搭配 reuse 機制,而不是像範例這樣把全部 imageView 一次加入。照片瀏覽器是記憶體消耗的大戶,重用是必須的。

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