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

用 UIScrollView 打造無限循環圖片瀏覽器:從 UIView 基礎到實戰

編輯:iOS 開發綜合

一、寫在前面

UIKit 提供了大量現成控件,但真正好用的往往是在這些控件的基礎上自己擴展出來的。逐一介紹每個控件意義不大,授人以魚不如授人以漁——把原理講通,找幾個有代表性的控件剖析,其餘自然觸類旁通。

本文的脈絡是:

  • UIView:所有控件的父類,先補齊基礎。
  • UIScrollView:滾動與縮放的核心。
  • 實戰:做一個無限循環的圖片瀏覽器。

二、先認識 UIView

UIScrollView 繼承自 UIView,所以在討論它之前,得先把父類的知識補上,否則看到某些方法會不知從何下手。

在 Xcode 中查一個類有哪些屬性和方法很簡單:按住 Option 鍵點擊類名即可跳轉到定義處。記住 iOS 全部 API 並不現實,學會查文件才是正解。

UIView 的標頭檔相當長,全截圖沒有意義,這裡只列出常用部分。

一個容易忽略的前提:上面所有位置屬性都是相對於父控件,而不是相對於螢幕。多數屬性單純易懂,我們重點看 autoresizingMask 與 transform。

三、autoresizingMask:讓控件隨螢幕旋轉自動伸縮

這個屬性在處理螢幕旋轉時經常用到,值是一個列舉:

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
    UIViewAutoresizingNone = 0,                     // 不自動調整
    UIViewAutoresizingFlexibleLeftMargin = 1 << 0,   // 自動調整左側距,右側距不變
    UIViewAutoresizingFlexibleWidth = 1 << 1,        // 自動調整自身寬度,左右距不變
    UIViewAutoresizingFlexibleRightMargin = 1 << 2,  // 自動調整右側距,左側距不變
    UIViewAutoresizingFlexibleTopMargin = 1 << 3,    // 自動調整頂部距,底部距不變
    UIViewAutoresizingFlexibleHeight = 1 << 4,       // 自動調整自身高度,上下距不變
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5  // 自動調整底部距,頂部距不變
};

真正的奧妙在於按位或組合。假設 autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin,iOS 會自動調整左側距離與自身寬度,右側距離保持不變,並保證左側距與寬度以相同比例伸縮。

舉例:在 iPhone 5 上,一個按鈕寬 200,左右邊距各 60(左側距與寬度比為 3:10)。從豎屏轉橫屏時,寬度由 320 變成 568(若有狀態列則為 548)。右側邊距不變仍為 60,因此左側邊距 = (568-60) × 3/13 ≈ 117,寬度 = (568-60) × 10/13 ≈ 391。

程式碼示範(純程式碼建立介面,自訂 KCMainViewController):

// AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    KCMainViewController *mainController = [[KCMainViewController alloc] init];
    self.window.rootViewController = mainController;
    self.window.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
    [self.window makeKeyAndVisible];
    return YES;
}
// KCMainViewController.m
@interface KCMainViewController () {
    UIButton *_btn;   // 私有成員變量,這種定義方式以後會常用到
}

@end

@implementation KCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _btn = [[UIButton alloc] initWithFrame:CGRectMake(60, 100, 200, 50)];
    _btn.backgroundColor = [UIColor orangeColor];
    [_btn setTitle:@"Hello,world!" forState:UIControlStateNormal];
    _btn.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
    [self.view addSubview:_btn];
}

#pragma mark 螢幕旋轉事件
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    NSLog(@"%@", NSStringFromCGRect(_btn.frame));
}

@end

注意我把 window 背景設為灰色,畫面上雖然有一個 UIView,最終看到的卻是灰色——這說明 UIView 預設是透明的。

豎屏:

橫屏:

執行前請先全域隱藏狀態列,兩個設定缺一不可:

  1. info.plist 中 Status bar is initially hidden 設為 YES;
  2. info.plist 中 View controller-based status bar appearance 設為 NO。

四、transform:矩陣化的形變

transform 常被稱為形變屬性,本質是透過矩陣運算改變控件的大小、位置與角度。下面的例子同時示範 UIImageView 的常用操作。

#define NORMAL_COLOR     [UIColor colorWithRed:75/255.0  green:160/255.0 blue:253/255.0 alpha:1]
#define HIGHLIGHTED_COLOR [UIColor colorWithRed:197/255.0 green:221/255.0 blue:249/255.0 alpha:1]

typedef void (^ButtonHandle)();

@interface KCTransformViewController () {
    UIImageView *_imageView;   // 圖片控件
    UIButton *_btnRotation;    // 旋轉按鈕
    UIButton *_btnScale;       // 縮放按鈕
    UIButton *_btnTranslate;    // 移動按鈕
}
@end

@implementation KCTransformViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addImageView];
    [self addRotationButton];
    [self addScaleButton];
    [self addTranslateButton];
}

#pragma mark 添加圖片控件
- (void)addImageView {
    // 使用圖片名稱即可,系統會自動到資源檔中尋找
    UIImage *image = [UIImage imageNamed:@"promo_ios8.png"];
    // 用 initWithImage 初始化時,控件尺寸會自動等於圖片尺寸
    _imageView = [[UIImageView alloc] initWithImage:image];
    _imageView.frame = CGRectMake(20, 20, 280, 154);
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:_imageView];
}

#pragma mark 添加旋轉按鈕
- (void)addRotationButton {
    _btnRotation = [self getButton];
    _btnRotation.frame = CGRectMake(20, 400, 280, 30);
    [_btnRotation setTitle:@"旋轉" forState:UIControlStateNormal];
    [_btnRotation addTarget:self action:@selector(rotation:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnRotation];
}

#pragma mark 添加縮放按鈕
- (void)addScaleButton {
    CGRect scaleButtonFrame = _btnRotation.frame;
    scaleButtonFrame.origin.y += 40;
    _btnScale = [self getButton];
    _btnScale.frame = scaleButtonFrame;
    [_btnScale setTitle:@"縮放" forState:UIControlStateNormal];
    [_btnScale addTarget:self action:@selector(scale:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnScale];
}

#pragma mark 添加移動按鈕
- (void)addTranslateButton {
    CGRect translateButtonFrame = _btnScale.frame;
    translateButtonFrame.origin.y += 40;
    _btnTranslate = [self getButton];
    _btnTranslate.frame = translateButtonFrame;
    [_btnTranslate setTitle:@"移動" forState:UIControlStateNormal];
    [_btnTranslate addTarget:self action:@selector(translate:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnTranslate];
}

#pragma mark 圖片旋轉(btn 為當前點擊的按鈕)
- (void)rotation:(UIButton *)btn {
    [self animation:^{
        CGFloat angle = M_PI_4;  // M 開頭的宏都與數學相關,M_PI_4 即 π/4
        // CGAffineTransformMakeRotation 不會在既有角度上疊加,
        // 所以連點第二次就不會再轉了:
        // _imageView.transform = CGAffineTransformMakeRotation(angle);
        // 改用 CGAffineTransformRotate 在原基礎上累加
        _imageView.transform = CGAffineTransformRotate(_imageView.transform, angle);
    }];
}

#pragma mark 圖片縮放
- (void)scale:(UIButton *)btn {
    // 通常直接用 UIView 的靜態方法做動畫,而不是自己包一層
    [UIView animateWithDuration:0.5 animations:^{
        CGFloat scaleOffset = 0.9;
        _imageView.transform = CGAffineTransformScale(_imageView.transform, scaleOffset, scaleOffset);
    }];
}

#pragma mark 圖片移動
- (void)translate:(UIButton *)btn {
    [self animation:^{
        CGFloat translateY = 50;
        _imageView.transform = CGAffineTransformTranslate(_imageView.transform, 0, translateY);
    }];
}

#pragma mark 動畫執行方法(僅為示範原理,實作可直接用 animateWithDuration)
- (void)animation:(ButtonHandle)handle {
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5];
    handle();
    [UIView commitAnimations];
}

#pragma mark 統一按鈕樣式
- (UIButton *)getButton {
    UIButton *button = [[UIButton alloc] init];
    [button setTitleColor:NORMAL_COLOR forState:UIControlStateNormal];
    [button setTitleColor:HIGHLIGHTED_COLOR forState:UIControlStateHighlighted];
    return button;
}

@end

四個重點整理:

  1. 取得 CGAffineTransform 有多種方式,直接呼叫 CGAffineTransformMake 也行,但手動排矩陣很麻煩。iOS 已備好三個:MakeRotation(旋轉)、MakeScale(縮放)、MakeTranslation(移動)。
  2. 這三個 Make 方法不會在既有基礎上增量形變。若要持續累加,可自訂全域變數,但更省事的是用 iOS 提供的 Rotate、Scale、Translate 三個變體,它們會以傳入的 transform 為基礎疊加運算。
  3. ObjC 不允許直接修改物件結構體屬性的成員,只能整體賦值。也就是說 _btnRotation.frame.origin.x = 380; 是錯誤寫法,必須先取出 frame、改好、再整體寫回。
  4. iOS 的動畫開發非常簡單,而且動畫與邏輯完全分離——在兩個動畫方法之間改動控件屬性,執行時自動就有動畫。上面為了複習 block 而手寫了一個 animation 方法,實戰中直接呼叫 animateWithDuration 即可(它有多個重載版本)。

另外提醒:iOS 對 PNG 會做額外優化,圖片資源請優先使用 PNG。

五、UIScrollView 核心知識

顧名思義,這是一個負責滾動的視圖,使用頻率極高,而且常被當作其他控件的基礎——UITableView 就是繼承自它。先看常用屬性與方法:

contentSize、contentInset、contentOffset 三者關係圖:

Delegate 方法的執行順序值得記牢:

a. 拖動子控件時:開始拖拽 → 滾動 → 滾動…… → 停止拖拽 → 將要停止滾動 → 滾動 → 滾動…… → 停止滾動。

「減速」那段可能執行也可能不執行,取決於你是急停還是讓它帶著慣性滑行(就像剎車,急剎就沒有後續滑行)。但無論如何,滾動事件會持續觸發,因此若在其中做運算,務必留意效能。

b. 縮放子控件時:開始縮放 → 滾動 → 滾動…… → 停止縮放。同樣地,滾動事件會一路被呼叫。

一個簡單範例:

// KCScrollViewController.h
#import <UIKit/UIKit.h>

@interface KCScrollViewController : UIViewController

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIImageView *imageView;

@end
// KCScrollViewController.m
// 實作 UIScrollView 代理
@interface KCScrollViewController () <UIScrollViewDelegate>
@end

@implementation KCScrollViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // UIScreen 代表當前螢幕物件,applicationFrame 是可用內容區域
    _scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    _scrollView.contentMode = UIViewContentModeScaleToFill;
    [self.view addSubview:_scrollView];

    UIImage *image = [UIImage imageNamed:@"wwdc14-labs-hero-background.jpg"];
    _imageView = [[UIImageView alloc] initWithImage:image];
    [_scrollView addSubview:_imageView];

    // contentSize 必須設定,否則無法滾動;此處設為圖片大小
    _scrollView.contentSize = _imageView.frame.size;

    // 縮放:maximumZoomScale 必須大於 minimumZoomScale,
    // 同時要實作 viewForZoomingInScrollView:
    _scrollView.minimumZoomScale = 0.6;
    _scrollView.maximumZoomScale = 3.0;
    _scrollView.delegate = self;

    // 邊距不屬於內容部分,內容座標 (0,0) 指的是內容左上角,不含邊界
    // _scrollView.contentInset = UIEdgeInsetsMake(10, 20, 10, 20);

    // 指定顯示位置
    // _scrollView.contentOffset = CGPointMake(10, 0);

    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;

    // 關閉彈簧效果
    // _scrollView.bounces = NO;
}

#pragma mark 不實作此方法則無法縮放
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _imageView;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"scrollViewWillBeginDragging");
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"scrollViewDidEndDragging");
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    NSLog(@"scrollViewWillBeginDecelerating");
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"scrollViewDidEndDecelerating");
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
    NSLog(@"scrollViewWillBeginZooming");
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
    NSLog(@"scrollViewDidEndZooming");
}

#pragma mark 圖片小於螢幕時,縮放後讓它置中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    CGSize originalSize = _scrollView.bounds.size;
    CGSize contentSize = _scrollView.contentSize;

    CGFloat offsetX = originalSize.width > contentSize.width
                    ? (originalSize.width - contentSize.width) / 2 : 0;
    CGFloat offsetY = originalSize.height > contentSize.height
                    ? (originalSize.height - contentSize.height) / 2 : 0;

    _imageView.center = CGPointMake(contentSize.width / 2 + offsetX,
                                    contentSize.height / 2 + offsetY);
}

@end

預設情況下,縮放後的內容會被放在 contentOffset 的起始位置。若希望它置中,就必須像上面那樣自己維護位置。

延伸:ARC 的四個關鍵字

iOS 5 之後引入 ARC,編譯時自動幫你插入 retain / release,開發者不必手動管理。要注意的是 ARC 是編譯器特性,不是執行期特性——底層仍是引用計數,只是記憶體管理程式碼由編譯器代為產生。因此它的規則與 MRC 一致:只要有一個強引用指向物件,物件就不會被釋放。

strong(變數寫作 __strong):強引用,等同 retain。每次賦值計數 +1,只要還有色指針引用它,物件就不會銷毀。

weak(變數寫作 __weak):弱引用,等同 assign,但差別在於物件釋放後會自動設為 nil,避免垂懸指針。(assign 也能修飾物件型別屬性,只是沒有自動清空機制。)

unsafe_unretained(變數寫作 __unsafe_unretained):與 weak 類似,但物件釋放後不會清空,可能出現垂懸指針。它出現得比 weak 早(weak 在 iOS 5.0 / Lion 之後才有),目前保留主要是為了相容性,新專案建議直接用 weak。

__autoreleasing(只能修飾變數,不能修飾屬性):表示使用完畢後自動釋放,等同 MRC 下的 autorelease,常用於延遲釋放。

幾點補充:

  • 除 weak 之外,其他修飾關鍵字在 MRC 下使用不會報錯,但編譯時會被忽略,寫了也沒意義。例如 MRC 下用 __strong 修飾變數,效果等同沒寫。
  • __autoreleasing 主要用在「參數為 ObjC 物件指標的指標」(即 NSObject **obj)這種情況,最典型的就是 NSError。這類方法內部往往需要重建物件並寫回參數,加上 __autoreleasing 後編譯器會使用自動釋放池,兼顧正常釋放與外部變數的修改。很多時候我們沒顯式宣告,是因為編譯器已自動處理,但考慮效能時還是可以明確標註。

看個 strong 與 weak 的對比:

// KCPerson.m
- (NSString *)description {
    return [NSString stringWithFormat:@"no=%i", _no];
}
// main.m
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        // strong 示範
        __strong KCPerson *person1 = [[KCPerson alloc] init];
        __strong KCPerson *person2 = person1;
        person1.no = 1;
        NSLog(@"%@", person2);   // 輸出:no=1
        person1 = nil;
        NSLog(@"%@", person2);   // 輸出:no=1(person2 仍強引用該物件)

        // weak 示範
        __strong KCPerson *person3 = [[KCPerson alloc] init];
        __weak   KCPerson *person4 = person3;
        person3.no = 3;
        NSLog(@"%@", person4);   // 輸出:no=3
        person3 = nil;
        NSLog(@"%@", person4);   // 輸出:(null)
    }
    return 0;
}

person1 與 person2 都是強引用,所以 person1 設為 nil 時物件並未釋放;person3 是強引用而 person4 是弱引用,person3 一置 nil,物件失去唯一強引用立刻釋放,person4 也被自動清空為 nil。

strong——person1 與 person2 的關係:

weak——person3 與 person4 的關係:

三個結論:

  1. 記憶體管理針對的都是物件型別。strong / weak 都不能用在基本型別上,基本型別宣告為 assign 即可,不需要也不應該自行管理。
  2. 所有指標變數預設就是 __strong,因此通常省略不寫。
  3. 物件一旦沒有強引用,即使仍存在弱引用也會被釋放,同時弱引用會被設為 nil。

回頭看前面 scrollView 那些屬性為什麼宣告成 strong?改成 weak 行不行?答案是不行。Xcode 會直接警告:「Assigning retained object to weak variable; object will be released after assignment」。原因前面已經講過——_scrollView = [[UIScrollView alloc] initWithFrame:...] 賦值完成後,這個物件只有一個弱引用指向它,執行期立刻就被釋放了。

那為什麼用 Storyboard 時系統產生的屬性預設是 weak 卻不會出問題?因為它有一個頂層物件持有強引用。由此得到實務結論:

  1. 用 strong / weak 取代舊的 retain / assign(基本型別仍用 assign);
  2. 用 IBOutlet 修飾的屬性(即 Storyboard 上的元件)用 weak;
  3. 非 Storyboard 元件(純程式碼建立的介面)用 strong。

六、實戰:無限循環圖片瀏覽器

這個例子要解決兩個問題。

問題一:如何無限循環?

在 UIScrollView 中放控件並設定 contentSize 後就能滾動。要讓它無限循環,只有兩條路:無限疊加圖片,或者滑到最後一張時立刻接回第一張。前者顯然不現實,所以採第二種。

做法很單純:在頭尾各多放一張圖(共 n+2 個)。例如有 5 張圖,就依序放:圖5、圖1、圖2、圖3、圖4、圖5、圖1。從圖1 往後滑到圖5 時,因為最後一張是圖1,使用者會感覺「繞回來了」;等這張完全顯示後,迅速把 contentOffset 設到第二個 UIImageView(真正的圖1),使用者就能繼續往後滑。往前滑同理,滑到第一張(圖5)時立刻把 offset 設到第 6 張。

問題二:如何優化效能?

圖片一多,n+2 個 UIImageView 全載入記憶體是我們不樂見的。仔細看會發現:其實 3 個 UIImageView 就夠了(用兩個也能實作,可以自行思考)。

策略是:永遠保持顯示中間那個 UIImageView,滾動時動態改寫三者的圖片。例如預設放 圖5 / 圖1 / 圖2,當前顯示中間的圖1。往後滑看到圖2 且完全顯示後,迅速把三個 view 重設為 圖1 / 圖2 / 圖3,再用 contentOffset 把中間那個(圖2)拉回可視區。繼續往後看到圖3,滑完後重設為 圖2 / 圖3 / 圖4……如此一來,使用者得到循環的錯覺,記憶體卻只佔三張圖。往前滑的原理完全對稱。

具體實作

先準備資料。把圖片資訊存進 plist,方便日後擴充;key 是圖檔名,value 是顯示在畫面上方的描述文字。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>0.jpg</key> <string>iphone 5s</string>
    <key>1.jpg</key> <string>iphone 5c</string>
    <key>2.jpg</key> <string>ipad mini with retina</string>
    <key>3.jpg</key> <string>ipad air</string>
    <key>4.jpg</key> <string>ipod</string>
    <key>5.jpg</key> <string>ipod touch</string>
    <key>6.jpg</key> <string>mac book pro</string>
    <key>7.jpg</key> <string>mac book air</string>
    <key>8.jpg</key> <string>imac</string>
</dict>
</plist>

圖檔依序命名為 0.jpg ~ 8.jpg。主程式集中在自訂的 KCMainViewController:一個 UIScrollView、三個 UIImageView 顯示圖片、一個 UILabel 顯示描述、一個 UIPageControl 顯示頁數。

#define SCREEN_WIDTH   320
#define SCREEN_HEIGHT  568
#define IMAGEVIEW_COUNT 3

@interface KCMainViewController () <UIScrollViewDelegate> {
    UIScrollView *_scrollView;
    UIImageView *_leftImageView;
    UIImageView *_centerImageView;
    UIImageView *_rightImageView;
    UIPageControl *_pageControl;
    UILabel *_label;
    NSMutableDictionary *_imageData;   // 圖片資料
    int _currentImageIndex;            // 當前圖片索引
    int _imageCount;                   // 圖片總數
}
@end

@implementation KCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadImageData];    // 載入資料
    [self addScrollView];    // 滾動控件
    [self addImageViews];    // 三個圖片控件
    [self addPageControl];   // 分頁控件
    [self addLabel];         // 描述控件
    [self setDefaultImage];  // 預設圖片
}

#pragma mark 載入圖片資料
- (void)loadImageData {
    // 讀取 App bundle 中的 plist
    NSString *path = [[NSBundle mainBundle] pathForResource:@"imageInfo" ofType:@"plist"];
    _imageData = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    _imageCount = (int)_imageData.count;
}

#pragma mark 滾動控件
- (void)addScrollView {
    _scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:_scrollView];

    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(IMAGEVIEW_COUNT * SCREEN_WIDTH, SCREEN_HEIGHT);

    // 初始顯示中間那張
    [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:NO];

    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
}

#pragma mark 三個圖片控件
- (void)addImageViews {
    _leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _leftImageView.contentMode = UIViewContentModeScaleAspectFit;
    [_scrollView addSubview:_leftImageView];

    _centerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _centerImageView.contentMode = UIViewContentModeScaleAspectFit;
    [_scrollView addSubview:_centerImageView];

    _rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(2 * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _rightImageView.contentMode = UIViewContentModeScaleAspectFit;
    [_scrollView addSubview:_rightImageView];
}

#pragma mark 預設顯示的圖片
- (void)setDefaultImage {
    _leftImageView.image   = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", _imageCount - 1]];
    _centerImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", 0]];
    _rightImageView.image  = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", 1]];

    _currentImageIndex = 0;
    _pageControl.currentPage = _currentImageIndex;

    NSString *imageName = [NSString stringWithFormat:@"%i.jpg", _currentImageIndex];
    _label.text = _imageData[imageName];
}

#pragma mark 分頁控件
- (void)addPageControl {
    _pageControl = [[UIPageControl alloc] init];

    // sizeForNumberOfPages: 會依頁數回傳合適尺寸
    CGSize size = [_pageControl sizeForNumberOfPages:_imageCount];
    _pageControl.bounds = CGRectMake(0, 0, size.width, size.height);
    _pageControl.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT - 100);

    _pageControl.pageIndicatorTintColor = [UIColor colorWithRed:193/255.0 green:219/255.0 blue:249/255.0 alpha:1];
    _pageControl.currentPageIndicatorTintColor = [UIColor colorWithRed:0 green:150/255.0 blue:1 alpha:1];
    _pageControl.numberOfPages = _imageCount;

    [self.view addSubview:_pageControl];
}

#pragma mark 描述控件
- (void)addLabel {
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 30)];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.textColor = [UIColor colorWithRed:0 green:150/255.0 blue:1 alpha:1];
    [self.view addSubview:_label];
}

#pragma mark 滾動停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self reloadImage];   // 重新載入三張圖

    // 移回中間
    [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:NO];

    _pageControl.currentPage = _currentImageIndex;

    NSString *imageName = [NSString stringWithFormat:@"%i.jpg", _currentImageIndex];
    _label.text = _imageData[imageName];
}

#pragma mark 重新載入圖片
- (void)reloadImage {
    int leftImageIndex, rightImageIndex;
    CGPoint offset = [_scrollView contentOffset];

    if (offset.x > SCREEN_WIDTH) {
        // 向右滑:索引 +1(取模實現循環)
        _currentImageIndex = (_currentImageIndex + 1) % _imageCount;
    } else if (offset.x < SCREEN_WIDTH) {
        // 向左滑:索引 -1
        _currentImageIndex = (_currentImageIndex + _imageCount - 1) % _imageCount;
    }

    _centerImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", _currentImageIndex]];

    leftImageIndex  = (_currentImageIndex + _imageCount - 1) % _imageCount;
    rightImageIndex = (_currentImageIndex + 1) % _imageCount;

    _leftImageView.image  = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", leftImageIndex]];
    _rightImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%i.jpg", rightImageIndex]];
}

@end

這裡要特別提醒:在滾動相關的方法中操作要格外謹慎。前面說過滾動事件會高頻循環觸發,非常耗效能,能不在其中做的事就別做。所以上面的核心邏輯刻意集中在 scrollViewDidEndDecelerating——一次完整滾動只會執行一次的時機。

整套實作的精髓其實只有兩句話:用「頭尾複本」欺騙視覺,用「三個視圖輪替」控制記憶體。理解這兩點之後,把它改造成支援手勢縮放、加上網路載入與快取,都只是自然延伸而已。

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