這三個屬性名字很像、作用完全不同,是滾動視圖最容易搞混的地方。用一個具體例子一次講清楚:假設 frame = (0, 0, 320, 480),contentSize = (320, 960)。
它描述的是內容本身的尺寸,也就是告訴 scrollView「你的世界有多大」。上例中寬度與 frame 相同、高度是 frame 的兩倍,所以這個 scrollView 可以上下滾動,可滾動的總範圍就是 960。
contentSize 是滾動能不能發生的決定因素:若 contentSize 小於或等於 frame,就完全不會滾動,此時 contentOffset 永遠是 (0, 0)。
它是內容原點相對於視圖原點的位移量。以上例而言,如果你一路拉到最底部,contentOffset 就是 (0, 480)——y 位移了 480,此時畫面上顯示的是內容的第 480 到 960 點。
程式化滾動就是設定這個屬性,通常搭配 setContentOffset:animated:;而 scrollViewDidScroll: 回呼裡讀的也是它,無限循環、視差滾動、下拉刷新都靠監看這個值實作。
它是內容的頂點相對於 scrollView 邊界的內縮距離,結構是 UIEdgeInsetsMake(top, left, bottom, right)。
例如設 contentInset = (100, 0, 0, 0),內容就會從 scrollView 的 y = 100 處開始顯示,頂部空出 100pt。這個屬性的關鍵特性是:它會讓 contentOffset 變成負值(初始為 (0, -100)),所以即使 contentSize 等於 frame,內容仍然能被往下拉出那塊空白。
下拉刷新就是這樣做的:MJRefresh 把 header 藏在 -60 左右的 inset 裡,你往下拉時 offset 變得更負,header 就露出來了。
iOS 7 之後那個惱人的「table view 頂部自動留白」,背後也是系統在幫你調整 contentInset;iOS 11 起則多了 adjustedContentInset(唯讀)與 safeAreaInsets 的整合,實際生效的 inset 建議讀 adjustedContentInset 而非 contentInset。
UITableView 是 UIScrollView 的子類,上述屬性它都有,但 contentSize 不是由你設定,而是由資料來源方法自動算出來的:
- (NSInteger)numberOfSections; - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
它會把所有 section 與 row 的高度加總,當成 contentSize 的高度。
例如:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 100;
}
若每行預設高度 44,那麼 contentSize 的高度就是 100 × 44 = 4400。
把三者想成「紙有多大、你的視窗停在紙的哪個位置、紙的四周留了多少邊」就不會搞混了。