zoukankan      html  css  js  c++  java
  • IOS-tableViewCell重用机制

    IOS-tableViewCell重用机制

    首先介绍tableViewCell原生cell的使用和重用机制

    使用dequeueReusableCellWithIdentifier方法,这个方法会从缓存池中,搜索有没有可以重用的cell,然后如果有的话,会进行重用。

    - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"cellText";
    //如果我们在缓存区中没有获取到cell,会在这里自动创建一个cell,并且将这个cell的重用名设置为cell,这样,我们用完了这个cell之后,cell放到了缓存区中,我们可以用dequeueReusableCellWithIdentifier方法将cell从缓存区中提取出来,进行重用。
        }
    
        return cell;
    }

    自定义nib的重用机制

    • xib中指定cell的Class为自定义cell类型
      nibCell
    • 调用 tableView 的 registerNib:forCellReuseIdentifier:方法向数据源注册cell
    • 在cellForRowAtIndexPath中使用
      dequeueReuseableCellWithIdentifier :forIndexPath:
      获取重用的cell,若无重用的cell,将自动使用所提供的nib文件创建cell并返回(若使用旧式dequeueReuseableCellWithIdentifier:方法需要判断返回是否为空而进行新建)
    xxxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
    • 获取cell时若无可重用cell,将创建新的cell并调用其中的awakeFromNib方法,可通过重写这个方法添加更多页面内容

    自定义cellClass的重用机制

    • 重写自定义cell的initWithStyle:withReuseableCellIdentifier:方法进行布局
    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
    { 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) 
    { 
    // cell页面布局 
    [self setupView]; 
    } 
    return self; 
    } 
    • 为tableView注册cell,使用registerClass:forCellReuseIdentifier:方法注册(注意是Class)
    [_tableView registerClass:[xxxxxCell class] forCellReuseIdentifier:kCellIdentify]; 
    • 在cellForRowAtIndexPath中使用
      dequeueReuseableCellWithIdentifier:forIndexPath:
      获取重用的cell,若无重用的cell,将自动使用所提供的class类创建cell并返回
    xxxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath]; 
    • 获取cell时若无可重用cell,将调用cell中的initWithStyle:withReuseableCellIdentifier:方法创建新的cell

    总结:

    1. 在tableView的创建时,使用 registerClass: forCellReuseIdentifier: ,然后再使用dequeueReuseableCellWithIdentifier:,这样就相当于自动管理tableViewCell了,(cell如果可以重用,就直接重用了)

      但是我们也可以使用首先介绍tableViewCell原生cell的使用和重用机制 标题中的方式,来管理cell的重用机制,想过也是一样的。

    2. dequeueReuseableCellWithIdentifier: 方法:获取缓冲区中可以使用的cell,如果没有,但是已经使用registerClass: forCellReuseIdentifier: 注册了,那么他会自动创建。否则不会,需要手动创建。

  • 相关阅读:
    Java 8 —— Lambda表达式
    Calendar 学习
    No provider available for the service com.xxx.xxx 错误解决
    ContextLoaderListener错误
    pom文件中引入依赖成功了,但是jar包找不着
    https=http+ssl
    Spring boot学习笔记
    Spring cloud 学习笔记
    记录一些注解的含义
    Linux笔记
  • 原文地址:https://www.cnblogs.com/AbeDay/p/5026923.html
Copyright © 2011-2022 走看看