UI技術(shù)總結(jié)--UITableView

UITableView是我們用的最多的一個(gè)控件,所以對(duì)于UITableView重用機(jī)制的掌握也就成了我們必須了解的一個(gè)知識(shí)點(diǎn),對(duì)于UITableView重用機(jī)制的剖析網(wǎng)上已經(jīng)有相當(dāng)多的文章了,這里我結(jié)合圖片和代碼再來(lái)闡述一遍.
cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];

我們?cè)诰帉懘a的時(shí)候經(jīng)常會(huì)寫到這樣一段話,根據(jù)一個(gè)指定的標(biāo)識(shí)符來(lái)獲取到一個(gè)可重用的cell,那么這個(gè)實(shí)際上就使用到了UITableView的重用機(jī)制,用一張圖來(lái)解釋一下.


重用

實(shí)線包含起來(lái)的部分是顯示到屏幕上的部分,其中Cell3,cell4,cell5是完全顯示到屏幕上的,而cell2和cell6是只有一部分顯示到當(dāng)前屏幕.如果當(dāng)前正是向上滑動(dòng)的一個(gè)過(guò)程的話,那么cell1這個(gè)時(shí)候已經(jīng)被加入到了重用池當(dāng)中,因?yàn)樗呀?jīng)滾出到屏幕外了,如果繼續(xù)向上滑動(dòng)的話,那么這個(gè)時(shí)候Cell7就會(huì)從重用池中根據(jù)指定的重用標(biāo)識(shí)符來(lái)取出一個(gè)可重用的cell.如果cell1到cell7全部用同一個(gè)重用標(biāo)識(shí)符的話,那么cell7就可以復(fù)用cell1創(chuàng)建的內(nèi)存,這樣就達(dá)到了這樣一個(gè)重用的目的.

接下來(lái),通過(guò)自定義一個(gè)控件來(lái)更深入理解UITableView的重用機(jī)制

首先,創(chuàng)建了一個(gè)叫ViewReusePool的類用于實(shí)現(xiàn)重用機(jī)制.

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
// 實(shí)現(xiàn)重用機(jī)制的類
@interface ViewReusePool : NSObject
// 從重用池中取出一個(gè)可重用的View
-(UIView *)dequeueReusableView;
// 向重用池中添加一個(gè)view
-(void)addUsingView:(UIView *)view;
// 重置方法,將當(dāng)前使用中的視圖移動(dòng)到可重用隊(duì)列當(dāng)中
-(void)reset;
@end
#import "ViewReusePool.h"
@interface ViewReusePool()
// 等待使用的隊(duì)列
@property(nonatomic,strong) NSMutableSet *waitUsedQueue;
// 使用中的隊(duì)列
@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;
    }
    // 進(jìn)行隊(duì)列移動(dòng)
    [_waitUsedQueue removeObject:view];
    [_usingQueue addObject:view];
    return view;
}

-(void)addUsingView:(UIView *)view
{
    if (!view) {
        return;
    }
    //添加視圖到使用中的隊(duì)列
    [_usingQueue addObject:view];
}

-(void)reset
{
    UIView *view = nil;
    while ((view = [_usingQueue anyObject])) {
        // 從使用隊(duì)列中移除
        [_usingQueue removeObject:view];
        // 加入等待隊(duì)列中
        [_waitUsedQueue addObject:view];
    }
}
@end

這部分的代碼簡(jiǎn)單明了的描述了重用機(jī)制的實(shí)現(xiàn)原理.接下來(lái)自定義一個(gè)使用了ViewReusePool重用機(jī)制的IndexedTableView.實(shí)現(xiàn)了類似索引條的功能.

#import <UIKit/UIKit.h>
@protocol IndexedTableViewDataSource <NSObject>
// 獲取一個(gè)tableview的字母索引條數(shù)據(jù)的方法
- (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滾動(dòng)
        [self.superview insertSubview:containerView aboveSubview:self];
    }
    if (!reusePool) {
        reusePool = [[ViewReusePool alloc]init];
    }
    // 標(biāo)記所有視圖為可重用狀態(tài)
    [reusePool reset];
    // reload字母索引條
    [self reloadIndexBar];
}

-(void) reloadIndexBar
{
    // 獲取字母索引條的顯示內(nèi)容
    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];
        //從重用池中取出一個(gè)button來(lái)
        UIButton *button = (UIButton *)[reusePool dequeueReusableView];
        // 如果沒(méi)有可重用的button就創(chuàng)建一個(gè)
        if (!button) {
            button = [[UIButton alloc]initWithFrame:CGRectZero];
            button.backgroundColor = [UIColor whiteColor];
            //注冊(cè)button到重用池中
            [reusePool addUsingView:button];
            NSLog(@"新建了一個(gè)button");
        }else{
            NSLog(@"button 重用了");
        }
        //添加button到父視圖控件
        [containerView addSubview:button];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //設(shè)置button的坐標(biāo)
        [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并實(shí)現(xiàn)自定義的重用功能.

#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];
    //創(chuàng)建一個(gè)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;
    // 設(shè)置tableview的索引數(shù)據(jù)源
    tableView.indexDataSource = self;
    [self.view addSubview:tableView];
    //創(chuàng)建一個(gè)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];
    
    //數(shù)據(jù)源
    dataSource = [NSMutableArray array];
    for (int i = 0; i < 100; i++) {
        [dataSource addObject:@(i + 1)];
    }
}

#pragma mark IndexedTableViewDataSource
-(NSArray<NSString *> *)indexTitlesForIndexTableView:(UITableView *)tableView
{
    //奇數(shù)次調(diào)用返回6個(gè)字母,偶數(shù)次調(diào)用返回11個(gè)
    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];
    // 如果重用池當(dāng)中沒(méi)有可重用的cell,那么創(chuàng)建一個(gè)cell
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    // 文案設(shè)置
    cell.textLabel.text = [[dataSource objectAtIndex:indexPath.row]stringValue];
    return cell;
}
-(void)doAction{
    [tableView reloadData];
}
@end

運(yùn)行一下可以看出是這樣一個(gè)效果.



點(diǎn)擊reloadData會(huì)從重用池中取出可復(fù)用的button,沒(méi)有的話就創(chuàng)建,看看控制臺(tái)的打印.

剛進(jìn)去的時(shí)候,因?yàn)橹赜贸刂袥](méi)有button所以會(huì)創(chuàng)建6個(gè)button,并添加到重用池中.如下圖所示.
點(diǎn)擊reloadTable按鈕會(huì)復(fù)用之前的6個(gè)button,并創(chuàng)建5個(gè)新的button添加到重用池中.如下圖所示

這個(gè)時(shí)候,重用池中已經(jīng)有11個(gè)button了,如果當(dāng)前屏幕的button數(shù)不超過(guò)這個(gè)數(shù)的話,就會(huì)一直復(fù)用重用池中的button不會(huì)再創(chuàng)建新的button,這樣減少了內(nèi)存的開(kāi)銷.


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,621評(píng)論 1 32
  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,194評(píng)論 8 265
  • 1、通過(guò)CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明AI閱讀 16,172評(píng)論 3 119
  • 整個(gè)世界都不知道誰(shuí)在等誰(shuí)?也許每個(gè)人都會(huì)路過(guò)彼此,但是總有那么一個(gè)人,即使看不到卻能感覺(jué)到。每天清晨的第一縷陽(yáng)光射...
    佛前的那朵青蓮閱讀 269評(píng)論 0 0
  • 為什么要選擇APP開(kāi)發(fā)?APP開(kāi)發(fā)和小程序開(kāi)發(fā)有什么區(qū)別? 在移動(dòng)互聯(lián)網(wǎng)時(shí)代,APP也成為移動(dòng)互聯(lián)網(wǎng)時(shí)代的必備工具...
    小姐姐muaaaa閱讀 280評(píng)論 0 2

友情鏈接更多精彩內(nèi)容