tableViewCell 复用

2017-03-29  本文已影响57人  orilme

1、tableViewCell复用介绍
tableView在使用过程中,苹果内部会做一些处理。其实简单说就是一个内部有一个cell池,里面放的就是你之前创建过的cell。如果资源丰富,则会保存一些UITableViewCell对象放入到cell池,在需要调用的时候迅速的返回,而不用创建。如果资源紧缺,cell池会自动清理一些多余的UITableViewCell对象。至于有多少cell,这个内部会自动控制。
2、tableviewCell复用的两个方法
dequeueReusableCellWithIdentifier:forIndexPath: (iOS6引入)

//必须与register方法配套使用,否则返回的cell可能为nil,会crash
[slef.myTableView registerClass:[MyCell class] forCellReuseIdentifier:NSStringFromClass([MyCell class])];
MyCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MyCell class]) forIndexPath:indexPath];

dequeueReusableCellWithIdentifier: (iOS2开始使用)

MyCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MyCell class])];
//返回cell可能为nil,判断为nil时创建新的cell
if (cell == nil) {
    cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([MyCell class])];
 }

3、注意,重取出来的cell是有可能捆绑过数据或者加过子视图的,所以,如果有必要,要清除数据(如label的边框),从而使其显示正确的内容。

4、注册不同类型的cell或者不复用,此处以不复用为例

@property (nonatomic, strong) NSMutableDictionary *cellDic;//放cell的标识符

// 每次先从字典中根据IndexPath取出唯一标识符
NSString *identifier = [_cellDic objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
// 如果取出的唯一标示符不存在,则初始化唯一标示符,并将其存入字典中,对应唯一标示符注册Cell
if (identifier == nil) {
   identifier = [NSString stringWithFormat:@"%@%@", @"cell", [NSString stringWithFormat:@"%@", indexPath]];
   [_cellDic setValue:identifier forKey:[NSString stringWithFormat:@"%@", indexPath]];
   // 注册Cell
   [self.tableview registerClass:[MyCell class]  forCellWithReuseIdentifier:identifier];
}
    
MyCell *cell = [tableView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
上一篇 下一篇

猜你喜欢

热点阅读