UITableView 简单效果图如下:
UITableView 简单效果图
- UITableViewController
UITableViewController 可以作为 UITableView 的视图控制器、数据源和委托对象,他们之间的关系如下图所示:
UITableView 和 UITableViewController 之间的关系
UITableViewController 的指定初始化方法是 initWithStyle:,调用时需要传入一个 UITableViewStyle 类型的常数 (UITableViewStylePlain 或 UITableViewStyleGrouped)。
- UITableView 数据源
在 Cocoa Touch 中,UITableView 对象会自己查询另一个对象以获得需要显示的内容,这个对象就是 UITableView 的数据源,也就是 dataSource 属性所指向的对象。
这里涉及到了一种常见的设计模式:某个对象中有一种可修改的数据,但是除该对象之外,其他对象只能访问该数据,而不能修改它。示例代码 (部分) 如下:
// .h 文件
@property (nonatomic, readonly) NSArray *allItems;
// .m 文件
@property (nonatomic) NSMutableArray *privateItems; /**< 内部可变数组 */
/** 注意:方法返回值类型为 NSArray, 但实际返回的是 NSMutableArray 类型,这样是可以的;反之则不行 */
- (NSArray *)allItems {
return self.privateItems;
}
当某个 UITableView 对象要显示表格内容时,会向自己的数据源(dataSource 属性所指向的对象)发送一系列消息,其中包括必需方法和可选方法。示例代码:
// 该方法(必需方法)会返回一个整型值,代表 UITableView 对象显示的行数。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[[BNRItemStore sharedStore] allItems] count];
}
参数
section作用:UITableView对象可以分段显示数据,每个表格段(section)包含一组独立的行。
UITableViewDataSource 协议的另一个必需实现的方法是 tableView:cellForRowAtIndexPath:
- UITableViewCell
表所显示的每一行都是一个独立的视图,这些视图是 UITableViewCell 对象。
负责显示 UITableViewCell 对象所代表的数据,是 contentView 所包含的三个子视图:两个 UILabel 对象(textLabel 和 detailTextLabel),一个 UIImageView 对象,如下图所示:
UITableViewCell 的视图层次结构
UITableViewCell 使用方法,示例代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 创建 UITableViewCell 对象,风格使用默认的 UITableViewCellStyleDefault
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
// 获取 allItems 的第 n 个 BNRItem 对象,然后将该 BNRItem 对象的描述信息赋给 UITableViewCell 对象的 textLabel
// 这里的 n 是该 UITableViewCell 对象所对应的表格行索引
NSArray *items = [[BNRItemStore sharedStore] allItems];
BNRItem *item = items[indexPath.row];
cell.textLabel.text = [item description];
return cell;
}
- 重用 UITableViewCell 对象
示例代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 创建或重用 UITableViewCell 对象
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
NSArray *items = [[BNRItemStore sharedStore] allItems];
BNRItem *item = items[indexPath.row]; //0-9
cell.textLabel.text = [item description];
return cell;
}
为了重用 UITableViewCell 对象,必须将创建的过程交给系统管理——需要告诉表视图,如果对象池中没有 UITableViewCell 对象,应该初始化哪种类型 UITableViewCell 对象。需要向表视图注册应该使用的 UITableViewCell,示例代码:
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}
《iOS编程(第4版)》 笔记










网友评论
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
这两行一个是self。tableview 一个是 tableview 如果 dequeue 这个方法也写成 self。 会不会不行?