UI技術總結--UITableView重用機制
UITableView是我們用的最多的一個控制元件,所以對於UITableView重用機制的掌握也就成了我們必須瞭解的一個知識點,對於UITableView重用機制的剖析網上已經有相當多的文章了,這裡我結合圖片和程式碼再來闡述一遍.
cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"]; 複製程式碼
我們在編寫程式碼的時候經常會寫到這樣一段話,根據一個指定的識別符號來獲取到一個可重用的cell,那麼這個實際上就使用到了UITableView的重用機制,用一張圖來解釋一下.

實線包含起來的部分是顯示到螢幕上的部分,其中Cell3,cell4,cell5是完全顯示到螢幕上的,而cell2和cell6是隻有一部分顯示到當前螢幕.如果當前正是向上滑動的一個過程的話,那麼cell1這個時候已經被加入到了重用池當中,因為它已經滾出到螢幕外了,如果繼續向上滑動的話,那麼這個時候Cell7就會從重用池中根據指定的重用識別符號來取出一個可重用的cell.如果cell1到cell7全部用同一個重用識別符號的話,那麼cell7就可以複用cell1建立的記憶體,這樣就達到了這樣一個重用的目的.
接下來,通過自定義一個控制元件來更深入理解UITableView的重用機制
首先,建立了一個叫 ViewReusePool
的類用於實現重用機制.
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> // 實現重用機制的類 @interface ViewReusePool : NSObject // 從重用池中取出一個可重用的View -(UIView *)dequeueReusableView; // 向重用池中新增一個view -(void)addUsingView:(UIView *)view; // 重置方法,將當前使用中的檢視移動到可重用隊列當中 -(void)reset; @end #import "ViewReusePool.h" @interface ViewReusePool() // 等待使用的佇列 @property(nonatomic,strong) NSMutableSet *waitUsedQueue; // 使用中的佇列 @property(nonatomic,strong) NSMutableSet *usingQueue; @end @implementation ViewReusePool -(instancetype)init { self = [super init]; if (self) { _waitUsedQueue = [NSMutableSet set]; _usingQueue = [NSMutableSet set]; } return self; } -(UIView *)dequeueReusableView { UIView *view = [_waitUsedQueue anyObject]; if (!view) { return nil; } // 進行佇列移動 [_waitUsedQueue removeObject:view]; [_usingQueue addObject:view]; return view; } -(void)addUsingView:(UIView *)view { if (!view) { return; } //新增檢視到使用中的佇列 [_usingQueue addObject:view]; } -(void)reset { UIView *view = nil; while ((view = [_usingQueue anyObject])) { // 從使用佇列中移除 [_usingQueue removeObject:view]; // 加入等待佇列中 [_waitUsedQueue addObject:view]; } } @end 複製程式碼
這部分的程式碼簡單明瞭的描述了重用機制的實現原理.接下來自定義一個使用了 ViewReusePool
重用機制的 IndexedTableView
.實現了類似索引條的功能.
#import <UIKit/UIKit.h> @protocol IndexedTableViewDataSource <NSObject> // 獲取一個tableview的字母索引條資料的方法 - (NSArray<NSString *> *)indexTitlesForIndexTableView:(UITableView *)tableView; @end @interface IndexedTableView : UITableView @property (nonatomic,weak) id<IndexedTableViewDataSource> indexDataSource; @end #import "IndexedTableView.h" #import "ViewReusePool.h" @interface IndexedTableView () { UIView *containerView; ViewReusePool *reusePool; } @end @implementation IndexedTableView -(void)reloadData{ [super reloadData]; if (!containerView) { containerView = [[UIView alloc]initWithFrame:CGRectZero]; containerView.backgroundColor = [UIColor whiteColor]; // 避免索引條隨著tableView滾動 [self.superview insertSubview:containerView aboveSubview:self]; } if (!reusePool) { reusePool = [[ViewReusePool alloc]init]; } // 標記所有檢視為可重用狀態 [reusePool reset]; // reload字母索引條 [self reloadIndexBar]; } -(void) reloadIndexBar { // 獲取字母索引條的顯示內容 NSArray <NSString *> *arrayTitles = nil; if ([self.indexDataSource respondsToSelector:@selector(indexTitlesForIndexTableView:)]) { arrayTitles = [self.indexDataSource indexTitlesForIndexTableView:self]; } //判斷字母索引條是否為空 if (!arrayTitles || arrayTitles.count <= 0) { containerView.hidden = YES; return; } NSUInteger count = arrayTitles.count; CGFloat buttonWidth = 60; CGFloat buttonHeight = self.frame.size.height / count; for (int i = 0; i < arrayTitles.count; i++) { NSString *title = arrayTitles[i]; //從重用池中取出一個button來 UIButton *button = (UIButton *)[reusePool dequeueReusableView]; // 如果沒有可重用的button就建立一個 if (!button) { button = [[UIButton alloc]initWithFrame:CGRectZero]; button.backgroundColor = [UIColor whiteColor]; //註冊button到重用池中 [reusePool addUsingView:button]; NSLog(@"新建了一個button"); }else{ NSLog(@"button 重用了"); } //新增button到父檢視控制元件 [containerView addSubview:button]; [button setTitle:title forState:UIControlStateNormal]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; //設定button的座標 [button setFrame:CGRectMake(0, i * buttonHeight, buttonWidth, buttonHeight)]; } containerView.hidden = NO; containerView.frame = CGRectMake(self.frame.origin.x + self.frame.size.width - buttonWidth, self.frame.origin.y, buttonWidth, self.frame.size.height); } @end 複製程式碼
最後在viewcontroller中新增IndexedTableView並實現自定義的重用功能.
#import "ViewController.h" #import "IndexedTableView.h" @interface ViewController ()<UITableViewDelegate,UITableViewDataSource,IndexedTableViewDataSource> { IndexedTableView *tableView;//帶有索引條的tableView UIButton *button; NSMutableArray *dataSource; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //建立一個tableview tableView = [[IndexedTableView alloc]initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height - 60) style:UITableViewStylePlain]; tableView.delegate = self; tableView.dataSource = self; // 設定tableview的索引資料來源 tableView.indexDataSource = self; [self.view addSubview:tableView]; //建立一個button button = [UIButton buttonWithType:UIButtonTypeSystem]; button.frame = CGRectMake(0, 20, self.view.frame.size.width, 40); button.backgroundColor = [UIColor redColor]; [button setTitle:@"reloadTable" forState:UIControlStateNormal]; [button addTarget:self action:@selector(doAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; //資料來源 dataSource = [NSMutableArray array]; for (int i = 0; i < 100; i++) { [dataSource addObject:@(i + 1)]; } } #pragma mark IndexedTableViewDataSource -(NSArray<NSString *> *)indexTitlesForIndexTableView:(UITableView *)tableView { //奇數次呼叫返回6個字母,偶數次呼叫返回11個 static BOOL change = NO; if (change) { change = NO; return @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K"]; }else{ change = YES; return @[@"A",@"B",@"C",@"D",@"E",@"F"]; } } #pragma mark UITableViewDataSource -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return dataSource.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"reuseId"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; // 如果重用池當中沒有可重用的cell,那麼建立一個cell if (!cell) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; } // 文案設定 cell.textLabel.text = [[dataSource objectAtIndex:indexPath.row]stringValue]; return cell; } -(void)doAction{ [tableView reloadData]; } @end 複製程式碼
執行一下可以看出是這樣一個效果.

點選reloadData會從重用池中取出可複用的button,沒有的話就建立,看看控制檯的列印.
剛進去的時候,因為重用池中沒有button所以會建立6個button,並新增到重用池中.如下圖所示.

點選reloadTable按鈕會複用之前的6個button,並建立5個新的button新增到重用池中.如下圖所示

這個時候,重用池中已經有11個button了,如果當前螢幕的button數不超過這個數的話,就會一直複用重用池中的button不會再建立新的button,這樣減少了記憶體的開銷.
