適配器的作用是讓介面彼此不相容的類別能夠協同工作:它包裝一個物件,對外暴露一組標準的互動介面。
如果你熟悉這個模式,會發現 Apple 是以「有點不同」的方式實踐它——用 Protocol 而非物件包裝。UITableViewDelegate、UIScrollViewDelegate、NSCoding、NSCopying 都是例子。以 NSCopying 來說,任何類別只要遵循它,就能提供一個標準的 copy 方法。
接下來我們動手做一個水平滾動視圖,示範如何以 delegate 協議讓它與具體資料型別完全解耦。

在專案導航區右鍵點擊 View 組,選擇 New File,使用 iOS / Cocoa Touch / Objective-C class 範本建立類別,命名為 HorizontalScroller,父類別設為 UIView。
打開 HorizontalScroller.h,在 @end 之後加入:
@protocol HorizontalScrollerDelegate <NSObject> @required // 詢問 delegate 要展示幾個視圖 - (NSInteger)numberOfViewsForHorizontalScroller:(HorizontalScroller *)scroller; // 詢問 delegate 指定索引處應回傳哪個視圖 - (UIView *)horizontalScroller:(HorizontalScroller *)scroller viewAtIndex:(int)index; // 告知 delegate 某索引的視圖被點擊了 - (void)horizontalScroller:(HorizontalScroller *)scroller clickedViewAtIndex:(int)index; @optional // 初始顯示的索引;未實作時預設為 0 - (NSInteger)initialViewIndexForHorizontalScroller:(HorizontalScroller *)scroller; @end
這裡同時有必需與可選方法。必需方法提供滾動視圖運作所不可或缺的資料:視圖數量、指定索引的視圖、以及點擊後的行為。可選方法則是初始索引,未實作時退回第一個。
讓協議繼承自 NSObject 協議是一條最佳實踐——遵循 NSObject 協議,或遵循一個本身已實現 NSObject 協議的類別,可確保你能對 delegate 發送 NSObject 定義的訊息。
由於 delegate 的定義在類別定義之後,編譯器在 @interface 處還看不到它,因此需要前置宣告:
@protocol HorizontalScrollerDelegate; @interface HorizontalScroller : UIView @property (weak) id<HorizontalScrollerDelegate> delegate; - (void)reload; @end
屬性宣告為 weak 是為了避免循環引用:若類別強引用 delegate,而 delegate 又強引用回來,記憶體就無法釋放。id<...> 的寫法則保證只有遵循該協議的類別才能被指派,保留了型別安全。reload 的作用等同 UITableView 的 reloadData,用來依最新資料重建視圖。
#import "HorizontalScroller.h"
// 1
#define VIEW_PADDING 10
#define VIEW_DIMENSIONS 100
#define VIEWS_OFFSET 100
// 2
@interface HorizontalScroller () <UIScrollViewDelegate>
@end
// 3
@implementation HorizontalScroller {
UIScrollView *scroller;
}
@end
三個註記點的含意:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
scroller = [[UIScrollView alloc]
initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
scroller.delegate = self;
[self addSubview:scroller];
UITapGestureRecognizer *tap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollerTapped:)];
[scroller addGestureRecognizer:tap];
}
return self;
}
滾動視圖完全填滿 HorizontalScroller;UITapGestureRecognizer 負責偵測專輯封面是否被點擊。
- (void)scrollerTapped:(UITapGestureRecognizer *)gesture {
CGPoint location = [gesture locationInView:gesture.view];
// 不能對 scroller.subviews 做完整 enumeration,
// 因為其中還混有我們自己加入的東西;只遍歷 delegate 提供的視圖
for (int index = 0; index < [self.delegate numberOfViewsForHorizontalScroller:self]; index++) {
UIView *view = scroller.subviews[index];
if (CGRectContainsPoint(view.frame, location)) {
[self.delegate horizontalScroller:self clickedViewAtIndex:index];
[scroller setContentOffset:
CGPointMake(view.frame.origin.x - self.frame.size.width / 2
+ view.frame.size.width / 2, 0)
animated:YES];
break;
}
}
}
關鍵在於:HorizontalScroller 除了知道自己可以向 delegate 發送這些訊息(因為對方保證遵循協議),對 delegate 的具體型別一無所知。這正是適配器模式想要的鬆耦合。
- (void)reload {
// 1 沒有 delegate 就什麼都不做
if (self.delegate == nil) return;
// 2 移除既有子視圖
[scroller.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[obj removeFromSuperview];
}];
// 3 xValue 為起始基準點,可透過修改 #define 調整
CGFloat xValue = VIEWS_OFFSET;
for (int i = 0; i < [self.delegate numberOfViewsForHorizontalScroller:self]; i++) {
// 4 依序向 delegate 索取視圖並定位
xValue += VIEW_PADDING;
UIView *view = [self.delegate horizontalScroller:self viewAtIndex:i];
view.frame = CGRectMake(xValue, VIEW_PADDING, VIEW_DIMENSIONS, VIEW_DIMENSIONS);
[scroller addSubview:view];
xValue += VIEW_DIMENSIONS + VIEW_PADDING;
}
// 5 設定 contentSize,使用者才能捲動
[scroller setContentSize:CGSizeMake(xValue + VIEWS_OFFSET,
self.frame.size.height)];
// 6 若有指定初始視圖則置中(此方法是可選的,需先檢查)
if ([self.delegate respondsToSelector:@selector(initialViewIndexForHorizontalScroller:)]) {
int initialView = [self.delegate initialViewIndexForHorizontalScroller:self];
[scroller setContentOffset:
CGPointMake(initialView * (VIEW_DIMENSIONS + (2 * VIEW_PADDING)), 0)
animated:YES];
}
}
何時呼叫 reload?資料變動時,以及滾動視圖被加入其他視圖時:
- (void)didMoveToSuperview {
[self reload];
}
didMoveToSuperview 正是重新載入的最佳時機。
- (void)centerCurrentView {
int xFinal = scroller.contentOffset.x + (VIEWS_OFFSET / 2) + VIEW_PADDING;
int viewIndex = xFinal / (VIEW_DIMENSIONS + (2 * VIEW_PADDING));
xFinal = viewIndex * (VIEW_DIMENSIONS + (2 * VIEW_PADDING));
[scroller setContentOffset:CGPointMake(xFinal, 0) animated:YES];
// 置中後視圖可能已改變,必須通知 delegate
[self.delegate horizontalScroller:self clickedViewAtIndex:viewIndex];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
willDecelerate:(BOOL)decelerate {
if (!decelerate) {
[self centerCurrentView];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
[self centerCurrentView];
}
計算時把目前偏移量、視圖尺寸與間距都納入考量。兩個 delegate 方法分別處理「拖動結束且未繼續慣性」與「慣性完全停止」兩種情況——兩者都需要重新置中。
回頭看這段程式碼:完全沒有涉及任何 Album 或 AlbumView 的資訊。這意味著滾動視圖是完全獨立、可複用的元件。
#import "HorizontalScroller.h"
#import "AlbumView.h"
@interface ViewController () <UITableViewDataSource, UITableViewDelegate,
HorizontalScrollerDelegate>
@end
在類別擴充中加上實例變數 HorizontalScroller *scroller;,接著只要實作三個方法,功能就出來了:
#pragma mark - HorizontalScrollerDelegate methods
- (void)horizontalScroller:(HorizontalScroller *)scroller clickedViewAtIndex:(int)index {
currentAlbumIndex = index;
[self showDataForAlbumAtIndex:index];
}
- (NSInteger)numberOfViewsForHorizontalScroller:(HorizontalScroller *)scroller {
return allAlbums.count;
}
- (UIView *)horizontalScroller:(HorizontalScroller *)scroller viewAtIndex:(int)index {
Album *album = allAlbums[index];
return [[AlbumView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)
albumCover:album.coverUrl];
}
順帶一提:#pragma mark 之後寫方法,是組織程式碼的通用做法。編譯器會忽略這些行,但 Xcode 的方法跳轉選單會把它們整理成粗體分節標題,導航方便很多。
接著補上載入方法:
- (void)reloadScroller {
allAlbums = [[LibraryAPI sharedInstance] getAlbums];
if (currentAlbumIndex < 0) {
currentAlbumIndex = 0;
} else if (currentAlbumIndex >= allAlbums.count) {
currentAlbumIndex = allAlbums.count - 1;
}
[scroller reload];
[self showDataForAlbumAtIndex:currentAlbumIndex];
}
最後在 viewDidLoad 中建立實例:
scroller = [[HorizontalScroller alloc]
initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
scroller.backgroundColor = [UIColor colorWithRed:0.24f green:0.35f blue:0.49f alpha:1];
scroller.delegate = self;
[self.view addSubview:scroller];
[self reloadScroller];
執行看看——水平滾動視圖出來了,但封面沒顯示。這是因為下載圖片的邏輯還沒寫。而這正好帶出下一個模式:觀察者模式。
設計上的三個約束:
三個條件放在一起看似矛盾,觀察者模式正是為此而生——下一篇接著談。