Cell的复用机制问题总结

建立方式汇总,注册和不注册Cell注册的两种方式
1.tableView registerNib:(nullable UINib *) forCellReuseIdentifier:(nonnull NSString *)
2.tableView registerClass:(nullable Class) forCellReuseIdentifier:(nonnull NSString *)

Cell注册的形式:

(1)系统cell
    1.注册
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    2.不注册
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
  if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

(2)自定义cell
    1.注册
    [self.tableView registerClass:[xxxxCell class] forCellReuseIdentifier:@"cell"];
    xxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

  2.不注册
    xxxxCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
  if (cell==nil) {
      cell=[[xxxxCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

(3)自定义cellXib注册
    1.注册(能够复用)
    [tableView registerNib:[UINib nibWithNibName:@"xxxxViewCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    xxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    2.不注册(不会复用,每一次都是从新建立)
     xxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@“xxxxCell" owner:self options:nil]lastObject];
    }
复用机制很少作赘述,只讲解一下注册的复用机制
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier: identifier] ;

这个方法的做用是,当咱们从重用队列中取cell的时候,若是没有,系统会帮咱们建立咱们给定类型的cell,若是有,则直接重用. 这种方式cell的样式为系统默认样式.在设置cell的方法中只须要:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 重用队列中取单元格 因为上面已经注册过单元格,系统会帮咱们作判断,不用再次手动判断单元格是否存在

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier forIndexPath:indexPath] ;

    return cell ;
}

注册和不注册的区别:
- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier; // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one. (返回给代理一个已经分配的cell,代替一个新的cell,若是没有已分配的cell,则返回nil,使用这个方法就不须要注册了) - (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0); // newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered 若是cell的identifier是注册过的,那么这个新列出的方法保证返回一个cell (有分配的就返回已分配的cell,没有返回新的cell)并适当调整大小,可省略cell空值判断步骤,用这个方法cell必须注册,不是自定义的cell,UITableViewCell也要注册
相关文章
相关标签/搜索