第二十一篇:UITableView的基本使用

1.如何展示数据

》UITableView需要一个数据源(dataSource)来显示数据

》UITableView会向数据源查询一共有多少行数据以及每一行显示什么数据等

》没有设置数据源的UITableView只是个空壳

》凡是遵守UITableViewDataSource协议的OC对象,都可以是UITableView的数据源

2.tableView展示数据的过程

(1).调用数据源的下面方法得知一共有多少组数据

– (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView;

(2).调用数据源的下面方法得知每一组有多少行数据

– (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section;

(3).调用数据源的下面方法得知每一行显示什么内容

– (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath;

3.Cell简介

》UITableView的每一行都是一个UITableViewCell,通过dataSource的tableView:cellForRowAtIndexPath:方法来初始化每一行

》UITableViewCell内部有个默认的子视图:contentView,contentView是UITableViewCell所显示内容的父视图,可显示一些辅助指示视图

》辅助指示视图的作用是显示一个表示动作的图标,可以通过设置UITableViewCell的accessoryType来显示,默认是UITableViewCellAccessoryNone(不显示辅助指示视图),其他值如下:

UITableViewCellAccessoryDisclosureIndicator (一个小箭头)

UITableViewCellAccessoryDetailDisclosureButton(小圆里有个小箭头)

UITableViewCellAccessoryCheckmark(打钩)

还可以通过cell的accessoryView属性来自定义辅助指示视图(比如往右边放一个开关)

》contentView下默认有3个子视图

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

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

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

UITableViewCellStyleDefault(没有detailTextLable描述)

UITableViewCellStyleSubtitle(有detailTextLable描述,显示两行)

UITableViewCellStyleValue1(有detailTextLable描述,显示一行)

UITableViewCellStyleValue2(没有imageView图片显示)

5.Cell的重用原理

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

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

》Cell的重用代码

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{// 1.定义一个cell的标识static NSString *ID = @"mjcell";// 2.从缓存池中取出cellUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];// 3.如果缓存池中没有cellif (cell == nil) {cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];}// 4.设置cell的属性…return cell;}

版权声明:本文为博主原创文章,未经博主允许不得转载。

临行之前,面对太多的疑问和不解:为何是一个人?

第二十一篇:UITableView的基本使用

相关文章:

你感兴趣的文章:

标签云: