UITableViewCell的循环利用方式

方式一

//被static修饰的局部变量:只会初始化一次,在整个程序运行过程中,只有一份内存
static NSString *ID = @"cell";
/**
 * 什么时候调用:每当有一个cell进入视野范围内就会调用
 */
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   //1. 设置重用标示
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    //2.如果cell为nil(缓存池找不到对应的cell)
    if(cell==nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableVIewCellStyleDefault reuseIdentifier:ID];
    }
    //3.显示数据
    cell.textLabel.text = [NSString stringWithFormat:@"testDate - %zd",indexPath.row];
    return cell;
}

方式二

  • 定义全局变量
//定义重用标示符
NSString *ID = @"cell";
  • 注册某个标识对应cell类型
//在这个方法中注册cell
-(void)viewDidLoad
{
    [super viewDidLoad];
    //注册某个标识对应的cell类型
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
}
  • 数据源方法中返回cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      //1.去缓存池中查找cell
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
      //2.显示数据
      cell.textLabel.text = [NSString stringWithFormat:@"testdata - %zd", indexPath.row];
      return cell;
}

方式三

  • 在storyboard中设置UITableView的Dynamic Prototypes Cell
Snip20150602_152.png
  • 设置cell的重用标识
Snip20150602_153.png
  • 在代码中利用重用标识获取cell

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     // 1. 重用标识,被static修饰的局部变量:只会初始化一次,在整个程序运行过程中,只有一份内存
    static NSString *ID = @"cell";
    // 2. 先根据cell的标识去缓存池中查找可循环利用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 3. 覆盖数据
    cell.textLabel.text = [NSString stringWithFormat:@"cell - %zd", indexPath.row];
    return cell;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容