iOS 【UIKit-UITableView】

来源:互联网 发布:淘宝首页 多次修改 编辑:程序博客网 时间:2024/06/14 08:53

要学这一部分首先我们要再回顾一下代理。

之前我们接触到过 <UITableViewDelegate> 这个协议,如果我们要学习UITableView,就要接触一个新的代理协议。也就是 <UITableViewDataSource>

比较一下这两个协议:(也算是 代理 小结一下)

代理 步骤:

//1、遵守协议,预先定义好方法,不实现,具体的实现工作由代理负责
//data source与delegate的区别:
//<控件名称+DataSource>  定义一些与数据操作有关的方法
//<控件名称+Delegate>    定义一些与事件、操作有关的方法,通常用来监听事件的

//2、连线

//3、代理方法
//① 方法名以控件名称开头(没有类前缀(类前缀:UI什么的。。)) ————  方便程序员快速找到相对应的协议方法
//② 方法的第一个参数一般是自己本身  ————  这意味着在方法中可以直接访问对象的属性和调用相关的方法
//③ 这些代理方法的返回值  ————  控制器向委托发送数据

那么下面通过这个代理引入我们这次要介绍的 UITableView 这个控件

UITableViewDataSource中两个 必须实现(@required)的方法,如果不在下面实现这两个方法,则会有下面两句警告:      (注意: @optional 选择实现)//Method 'tableView:numberOfRowsInSection:' in protocol 'UITableViewDataSource' not implemented//Method 'tableView:cellForRowAtIndexPath:' in protocol 'UITableViewDataSource' not implemented//下面举例说明一下这两个方法★//告知controller每个section需要加载多少个单元或多少行- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{//    Student *stu = self.dataList[section];//    return  stu.students.count;//    上面两句调用模型中数组元素个数的语句等同于底下这一句。//    这里需要说明一点,为什么我们在下面不用点语法调用students数组和count属性,因为直接在数组中取出的对象是id类型,id类型并不知道到底是什么类型,所以说我们不能调用点语法,而是要直接调用其getter方法。    return [[self.dataList[section] students] count];}★//返回UITableViewCell的实例(UITableViewCell是处理表格内部的类),用于构成table view.这个函数是一定要实现的。(有了这个方法,才有表格的产生)// 告诉表格控件,每一行cell单元格的明细、细节(通俗的讲,这个方法是控制表格内部的信息的)- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];    //    cell.textLabel.text = [NSString stringWithFormat:@"表格 第 %02d 组,第 %003d 行",indexPath.section,indexPath.row];//这里注意该语句前面出现了 汉字字符,所以后面可能不会出现提示。这是一个bug。        Student *stu = self.dataList[indexPath.section];//先取出该组中的Student对象        cell.textLabel.text = stu.students[indexPath.row];//每一行的text是对应Student对象中students数组属性中的内容,用行数来确定        //引入NSIndexPath    //@interface NSIndexPath (UITableView)  UITableView是NSIndexPath的一个类别(Category),为其添加了一个方法indexPathForRow    //    //+ (instancetype)indexPathForRow:(NSInteger)row inSection:(NSInteger)section;    //    //@property (nonatomic, readonly) NSInteger section; 表格 分组    //@property (nonatomic, readonly) NSInteger row; 表格 行    //    //@end        return cell;}另外还有第三个方法,一般也是要实现的。★//告知视图,有多少个section需要加载到table里(这是一个@optional方法,选择实现,但是我们一般是一定要实现这个方法的)// Default is 1 if not implemented   (如果没实现的话,默认为一个分组。在此我们引入了分组的概念)- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    return self.dataList.count;}下面的两个方法也是经常遇到的,我们可以选择实现:★//为每一个分组设置 标题文字- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{    return [self.dataList[section] title];}★//为每一个分组设置 尾部文字- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{    return [self.dataList[section] desc];}





6 0
原创粉丝点击