一、概述
我们经常需要显示大量数据,比如iPhone内置的通讯录应用。UITableView是UIScrollView的子类。在iPhone中,表视图是iPhone上的一个列,多个行的表;用户可以上下滚动来查看更多的数据。从用户的角度来看,创建一个表视图就是完成下面三个功能:
- 创建表视图
- 为每一行提供文本或图像
- 当用户选择某一行时,做出响应
一个表视图必须有个一个数据源,这是通过UITableViewDataSource协议来完成的。另外表视图通过UITableViewDelegate协议来实现表视图上的操作。一般而言,你会创建一个UITableViewController的子类,然后在这个子类上实现数据源和表视图的操作。
1.1 表视图的类型
表视图的显示风格分为两类:
1、不分组的显示---UITableViewStylePlain2、分组的显示---UITableViewStyleGrouped
对于分组的结构,每组叫做section,在section的每一行叫做表单元(Table Cell)
二、UITableView的常用方法
2.1 初始化一个表视图的方法
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style ;
2.2 表视图的相关配置方法
- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier ;//根据唯一标识,查找可重用表视图单元(UITableViewCell)对象
- (NSInteger)numberOfRowsInSection:(NSInteger)section ;//返回指定section的表视图行数
- (NSInteger)numberOfSections ;//返回表视图中的section数目
2.3 访问section和表单元(UITableViewCell)
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath ;//返回指定NSIndexPath的表单元,NSIndexPath对象代表在一个嵌套数组集合树的特定节点的路径。这条道路被称为索引路径。此处只要将NSIndexPath理解为一个可代表表单元位置的一个路径,根据这个NSIndexPath路径,可用定位到对应的表单元。
- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell ;//返回指定表单元的NSIndexPath路径信息
- (NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point;//返回指定了CGPoint的NSIndexPath路径信息
- (NSArray *)indexPathsForRowsInRect:(CGRect)rect;//返回指定CGRect的NSIndexPath路径信息数组
- (NSArray *)visibleCells;//返回可见的表单元(UITableViewCell)数组
- (NSArray *)indexPathsForVisibleRows;//返回可见的表单元的NSIndexPath路径信息数组
2.4 管理section
- (NSIndexPath *)indexPathForSelectedRow;//返回选中行的NSIndexPath路径信息
- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition;//
- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;//
2.5 插入和删除表单元(UITableViewCell)
- (void)beginUpdates
- (void)endUpdates
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
- (void)setEditing:(BOOL)editing animated:(BOOL)animate
2.6 表视图数据的加载
- (void)reloadData
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation
- (void)reloadSectionIndexTitles