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,這樣減少了內存的開銷.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章