zoukankan      html  css  js  c++  java
  • iOS开发 UITableView之cell

    1.cell简介

    UITableView的每一行都是一个UITableViewCell,通过dataSource的tableView:cellForRowAtIndexPath:方法来初始化每一行
    UITableViewCell内部有个默认的子视图:contentView,contentView是UITableViewCell所显示内容的父视图,可显示一些辅助指示视图
    辅助指示视图的作用是显示一个表示动作的图标,可以通过设置UITableViewCell的accessoryType来显示,默认是UITableViewCellAccessoryNone(不显示辅助指示视图),其他值如下:
    UITableViewCellAccessoryDisclosureIndicator      wps_clip_image-32321
    UITableViewCellAccessoryDetailDisclosureButton  wps_clip_image-32286
    UITableViewCellAccessoryCheckmark  wps_clip_image-8078
    还可以通过cell的accessoryView属性来自定义辅助指示视图(比如往右边放一个开关

     

    2.UITableViewCell的contentView

    contentView下默认有3个子视图

    其中2个是UILabel(通过UITableViewCell的textLabel和detailTextLabel属性访问)

    第3个是UIImageView(通过UITableViewCell的imageView属性访问)

    UITableViewCell还有一个UITableViewCellStyle属性,用于决定使用contentView的哪些子视图,以及这些子视图在contentView中的位置

    wps_clip_image-1003

    3.UITableViewCell结构

    wps_clip_image-2844

    4.Cell的重用原理

    iOS设备的内存有限,如果用UITableView显示成千上万条数据,就需要成千上万个UITableViewCell对象的话,那将会耗尽iOS设备的内存。要解决该问题,需要重用UITableViewCell对象

    重用原理:当滚动列表时,部分UITableViewCell会移出窗口,UITableView会将窗口外的UITableViewCell放入一个对象池中,等待重用。当UITableView要求dataSource返回UITableViewCell时,dataSource会先查看这个对象池,如果池中有未使用的UITableViewCell,dataSource会用新的数据配置这个UITableViewCell,然后返回给UITableView,重新显示到窗口中,从而避免创建新对象

    还有一个非常重要的问题:有时候需要自定义UITableViewCell(用一个子类继承UITableViewCell),而且每一行用的不一定是同一种UITableViewCell,所以一个UITableView可能拥有不同类型的UITableViewCell,对象池中也会有很多不同类型的UITableViewCell,那么UITableView在重用UITableViewCell时可能会得到错误类型的UITableViewCell

    解决方案:UITableViewCell有个NSString *reuseIdentifier属性,可以在初始化UITableViewCell的时候传入一个特定的字符串标识来设置reuseIdentifier(一般用UITableViewCell的类名)。当UITableView要求dataSource返回UITableViewCell时,先通过一个字符串标识到对象池中查找对应类型的UITableViewCell对象,如果有,就重用,如果没有,就传入这个字符串标识来初始化一个UITableViewCell对象

    5.Cell的重用代码

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    
    {
    
        // 1.定义一个cell的标识
    
          static NSString *ID = @"mycell";
    
        // 2.从缓存池中取出cell
    
          UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
        // 3.如果缓存池中没有cell
    
          if (cell == nil) {
    
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    
        }
    
        // 4.设置cell的属性...
    
          return cell;
    
    }
  • 相关阅读:
    使用 WebSphere Adapter for SAP Software V7.5 配置 SAP 系统和客户端之间的安全网络通信 (SNC)
    在 ubuntu 12.04 上安装 redmine
    配置nat稳定网络防病毒
    利用 Replication Handler 备份索引
    .NET 4.5对Base Class Library做出改善
    redmine 和 gitolite 的整合
    IBM Power7 服务器 Hypervisor 内存使用情况研究
    Word域代码的显示
    转载:深入分析MFC文档视图
    VIM常用指令
  • 原文地址:https://www.cnblogs.com/iyou/p/3634846.html
Copyright © 2011-2022 走看看