UIScrollView 的滑動效果並沒有什麼魔法,本質上只是不斷修改自身的 bounds 原點。理解這一點之後,僅用三十來行代碼就能複刻它的核心行為。當然,真正的 UIScrollView 要複雜得多——回彈、慣性滾動、縮放、一整套代理方法,這裡都不涉及。
每一個 UIView 都擁有屬於自己的坐標系,約定是 x 軸向右、y 軸向下:

值得注意的是,這個邏輯坐標系本身沒有邊界,它向四周無限延伸,並不關心其中子視圖的寬高。往裡面放四個色塊:

UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
redView.backgroundColor = [UIColor colorWithRed:0.815 green:0.007 blue:0.105 alpha:1];
UIView *greenView = [[UIView alloc] initWithFrame:CGRectMake(150, 160, 150, 200)];
greenView.backgroundColor = [UIColor colorWithRed:0.494 green:0.827 blue:0.129 alpha:1];
UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(40, 400, 200, 150)];
blueView.backgroundColor = [UIColor colorWithRed:0.29 green:0.564 blue:0.886 alpha:1];
UIView *yellowView = [[UIView alloc] initWithFrame:CGRectMake(100, 600, 180, 150)];
yellowView.backgroundColor = [UIColor colorWithRed:0.972 green:0.905 blue:0.109 alpha:1];
[mainView addSubview:redView];
[mainView addSubview:greenView];
[mainView addSubview:blueView];
[mainView addSubview:yellowView];
Apple 對 bounds 的描述是:這個矩形定義了視圖在其自身坐標系中的位置與大小。
可以這樣類比:一個視圖就像開在坐標平面上的窗口,bounds 描述的就是這個窗口的位置與尺寸。假設視圖寬 320、高 480,原點在 (0, 0),那麼它相當於整張坐標紙的一個觀察口,只呈現其中一小塊區域。落在窗口之外的內容依然存在,只是被裁剪掉了。

frame 的描述是:這個矩形定義了視圖在其父視圖坐標系中的位置與大小。
現在我們試著改動 bounds 的原點:
CGRect bounds = mainView.bounds;
bounds.origin = CGPointMake(0, 100);
mainView.bounds = bounds;

畫面看上去像是整個內容向上滾了 100 像素。從這個視圖自身的坐標系來看確實如此,但它在屏幕(父視圖)上的實際位置並沒有變——因為 frame 沒有被改動。
換個比喻會更直觀:把整張坐標平面想象成一幅可以上下拉動的透明幕布,把視圖想象成觀察這幅幕布的窗口。修改 bounds 的原點,就等於拉動幕布,於是原本在窗口外的內容進入了視野:

所以,修改 bounds 原點的實質是把整個坐標系向上平移。用戶主觀上覺得是「子視圖在動」,但子視圖的 frame 從頭到尾都沒變過。這正是 UIScrollView 滑動時真正發生的事情。
既然滾動只是改 bounds,那麼實現一個簡易版本就毫無難度:掛一個手勢識別器,按拖動偏移量去調整 bounds 原點。
@import UIKit;
@interface CustomScrollView : UIView
@property (nonatomic) CGSize contentSize;
@end
#import "CustomScrollView.h"
@implementation CustomScrollView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self == nil) {
return nil;
}
UIPanGestureRecognizer *gestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
[self addGestureRecognizer:gestureRecognizer];
return self;
}
- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer {
CGPoint translation = [gestureRecognizer translationInView:self];
CGRect bounds = self.bounds;
// 平移 bounds,但不允許越過 contentSize 所定義的範圍
CGFloat newBoundsOriginX = bounds.origin.x - translation.x;
CGFloat minBoundsOriginX = 0.0;
CGFloat maxBoundsOriginX = self.contentSize.width - bounds.size.width;
bounds.origin.x = fmax(minBoundsOriginX, fmin(newBoundsOriginX, maxBoundsOriginX));
CGFloat newBoundsOriginY = bounds.origin.y - translation.y;
CGFloat minBoundsOriginY = 0.0;
CGFloat maxBoundsOriginY = self.contentSize.height - bounds.size.height;
bounds.origin.y = fmax(minBoundsOriginY, fmin(newBoundsOriginY, maxBoundsOriginY));
self.bounds = bounds;
[gestureRecognizer setTranslation:CGPointZero inView:self];
}
@end
和真正的 UIScrollView 一樣,這個類也有 contentSize 屬性,需要由外部設置以確定可滾動區域;每次改動 bounds 時都要夾取到合法範圍,否則會拖出屏幕之外。


- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, 320, 568 - 64)];
self.scrollView.delegate = self;
self.scrollView.backgroundColor = [UIColor redColor];
[self.view addSubview:_scrollView];
/*
contentOffset 當前滾動位置
contentSize 滾動範圍(核心屬性)
contentInset 內容內縮邊距
directionalLockEnabled 是否鎖定單一方向滾動
bounces 到達邊界是否回彈
alwaysBounceVertical 垂直方向是否總是回彈
alwaysBounceHorizontal 水平方向是否總是回彈
pagingEnabled 是否整頁翻動
scrollEnabled 是否允許滾動
showsHorizontalScrollIndicator / showsVerticalScrollIndicator 滾動條顯示
scrollIndicatorInsets 滾動條內縮
indicatorStyle 滾動條樣式
decelerationRate 減速率
tracking / dragging / decelerating 當前交互狀態
delaysContentTouches 是否延遲響應滾動
canCancelContentTouches 是否允許取消 touch
minimumZoomScale / maximumZoomScale / zoomScale 縮放範圍
bouncesZoom / zooming / zoomBouncing 縮放狀態
scrollsToTop 點擊狀態欄是否回到頂部
*/
[self.scrollView flashScrollIndicators];
[self.scrollView setContentOffset:CGPointMake(320, 0) animated:YES];
}
// 只要內容發生滾動就會觸發
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
// 開始拖拽,一次有效滑動只調用一次
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
// 手指離開屏幕瞬間調用,decelerate 表示是否還會繼續慣性滾動
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
// 即將進入減速
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView;
// 減速結束,滾動停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
// 由代碼觸發的滾動動畫結束(無動畫則不調用)
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;
// 指定需要參與縮放的子視圖
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return nil;
}
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view;
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale;
// 是否允許點擊狀態欄回到頂部
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
return YES;
}
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView;
把 bounds 與 frame 的分工記住,滾動、縮放乃至某些自定義動畫的原理就都通了:frame 決定「我在父視圖的哪裡」,bounds 決定「我能看見內容的哪一部分」。修改前者是移動視窗,修改後者是移動內容。