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,这样减少了内存的开销.


©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,037评论 1 32
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,027评论 8 265
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,937评论 3 118
  • 整个世界都不知道谁在等谁?也许每个人都会路过彼此,但是总有那么一个人,即使看不到却能感觉到。每天清晨的第一缕阳光射...
    佛前的那朵青莲阅读 221评论 0 0
  • 为什么要选择APP开发?APP开发和小程序开发有什么区别? 在移动互联网时代,APP也成为移动互联网时代的必备工具...
    小姐姐muaaaa阅读 212评论 0 2