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

iOS 高效異構滾動視圖方案:LazyScrollView 開源解析

編輯:iOS 開發基礎

LazyScrollView 開源了,正好把背後的一些設計思路拿出來講清楚。

GitHub 專案:https://github.com/alibaba/LazyScrollView

如果是第一次接觸,建議先看原理說明:https://pingguohe.net/2016/01/31/lazyscroll.html。Demo 請直接 Clone 專案,切到 master 分支,開啟 LazyScrollViewDemo 目錄下的工程,用法都在 ViewController 這個類裡。

建立視圖

TMMuiLazyScrollView *scrollview = [[TMMuiLazyScrollView alloc] init];
scrollview.frame = self.view.bounds;
scrollview.dataSource = self;
[self.view addSubview:scrollview];

初始化方式與一般的 ScrollView 一樣,唯一要注意的是必須有一個實作 TMMuiLazyScrollViewDataSource 的類別,並指定給 dataSource。

實作 TMMuiLazyScrollViewDataSource

回傳項目數量,決定要產生幾個 rectModel:

- (NSUInteger)numberOfItemInScrollView:(TMMuiLazyScrollView *)scrollView

回傳 RectModel:

- (TMMuiRectModel *)scrollView:(TMMuiLazyScrollView *)scrollView rectModelAtIndex:(NSUInteger)index

TMMuiRectModel 有兩個屬性:muiID 是該視圖的唯一識別碼,absoluteRect 是它在 LazyScrollView 內的絕對座標。

按需提供視圖,當即將進入螢幕的視圖需要產生時,LazyScrollView 會呼叫這個方法:

- (UIView *)scrollView:(TMMuiLazyScrollView *)scrollView itemByMuiID:(NSString *)muiID

實作上通常先找可重複使用的視圖,沒有才新建:

LazyScrollViewCustomView *label = (LazyScrollViewCustomView *)[scrollView dequeueReusableItemWithIdentifier:@"testView"];
NSInteger index = [muiID integerValue];
if (!label) {
    label = [[LazyScrollViewCustomView alloc] initWithFrame:
        [(NSValue *)[rectArray objectAtIndex:index] CGRectValue]];
    label.textAlignment = NSTextAlignmentCenter;
    label.reuseIdentifier = @"testView";
}
label.frame = [(NSValue *)[rectArray objectAtIndex:index] CGRectValue];
label.text = [NSString stringWithFormat:@"%lu", (unsigned long)index];

流程就是:先從重複使用池撈一個,有的話更新 frame,沒有就新建並給一個 reuseIdentifier。LazyScrollView 為 UIView 做了一個 category,裡頭就有 reuseIdentifier,任何視圖都能綁定這個屬性;若沒賦值或給了 nil/空字串,系統就視為不重複使用。

刷新視圖

設定 contentSize 後 reload 即可:

scrollview.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds), 1230);
[scrollview reloadData];

視圖生命週期

實作 TMMuiLazyScrollViewCellProtocol 的三個方法,就能在生命週期節點插入自己的程式碼:

- (void)mui_prepareForReuse
即將被重複使用前呼叫,通常用來清空視圖上顯示的資料,概念等同 UITableViewCell 的 prepareForReuse。

- (void)mui_didEnterWithTimes:(NSUInteger)times
進入可視範圍時執行,times 是進入次數、從 0 起算。想重置可呼叫 resetViewEnterTimes。

- (void)mui_afterGetView
LazyScrollView 取得視圖之後執行,也就是 itemByMuiID 這個方法跑完之後。與 didEnterWithTimes 的差別在於 LazyScrollView 有 RenderBuffer 的概念——實際渲染的範圍比可視區域上下各多 20 像素,讓滾動更順,因此 afterGetView 會比它更早觸發。

後續方向

LazyScrollView 屬於相對底層的視圖層,在重複使用上提供了高度的彈性。更上層的封裝,例如類似 UICollectionView 的 Layout、更簡易的重複使用管理、組件的解析與賦值,都放在 Tangram 裡。關於 Tangram 可參考 https://pingguohe.net/2016/12/20/Tangram-design-and-practice.html,開源計畫也在進行中。

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