TableView基础(view上添加tableView)

来源:互联网 发布:软件质量属性 编辑:程序博客网 时间:2024/06/08 13:49

详解一下tableview,并涉及到常用的代理协议。后期直接创建tableviewController,可以省略遵守协议,以及告诉委托方当前是代理人这两部分涉及的代码
下面开始介绍tableview,由于是在view上添加,所以需要遵守代理协议:

#import "ViewController.h"@interface ViewController () <UITableViewDataSource, UITableViewDelegate>@end

添加tableview,以及设置delegate,soucedata等

- (void)viewDidLoad {    [super viewDidLoad];//    1.创建实例 设置frame 默认为UITableViewStyleGrouped(分组样式)//                            UITableViewStylePlain(无分组样式)//      xib建立的tableview相反,默认为UITableViewStylePlain 可以通过右侧属性修改    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];//    3.添加到父视图中    [self.view addSubview:tableView];//    4.设置数据源  (三问)    tableView.dataSource = self;//    5.设置代理      (一答)    tableView.delegate = self;}

开始实现必要的代理协议:

//一问 几个分区-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return 3;}//二问 每个分区有几行-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    if (section == 0) return 5;    if (section == 1) return 8;    return 10;}//三问-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    UITableViewCell *cell = [[UITableViewCell alloc]init];    switch (indexPath.section) {        case 0:            cell.textLabel.text = @"你好吗";            break;        case 1:            cell.textLabel.text = @"我不好";            break;        case 2:            cell.textLabel.text = @"你会聊天吗";            if (indexPath.row == 1) {                cell.textLabel.text = @"gun!!!!!";            }            break;    }    return cell;}

继续实现点击事件

//一答  选中某行 如何处理-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {    //indexPath 该参数中 存着 分区号 和 行号    NSInteger sectionNum = indexPath.section;    NSInteger rowNum = indexPath.row;    NSLog(@"点中了 第%ld个分区 的 第%ld行", sectionNum, rowNum);    //获取 选中行 对应 cell 对象    UITableViewCell *selectCell = [tableView cellForRowAtIndexPath:indexPath];    NSLog(@"点中行的 内容 %@", selectCell.textLabel.text);}//某行 被 反选时  如何处理-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {}

设置分区头以及分区尾

//设置分区头高-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{    return 20;}//设置分区尾高-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{    return 80;}//设置 分区头  DataSource协议中的方法-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {    return [NSString stringWithFormat:@"这是第%ld个分区 头", section];}//设置 分区尾  DataSource协议中的方法-(NSString*)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {    return [NSString stringWithFormat:@"这是第%ld个分区 尾", section];}

实现效果如下:
这里写图片描述