UITableView的基本使用方法

1.什么时候需要使用UITableView?

    官方文档如下

  • To let users navigate through hierarchically structured data

  • To present an indexed list of items

  • To display detail information and controls in visually distinct groupings

  • To present a selectable list of options

简单理解就是现实的数据具有一定的层次结构


2.UITableView数据的展示通过Delegate和DataSource来配置(这个很重要!!!)

3.UITableView的类型 plain(无间隔)和grouped(段之间有间隔)类型

具体代码

1.创建TableView

 @interface ViewController ()<UITableViewDelegate,UITableViewDataSource>  //这两个协议必须服从

1 //创建一个TableView对象
2     self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
3     //设置delegate和DataSouce
4     _tableView.delegate = self;
5     _tableView.dataSource = self;
6     //添加到界面上
7     [self.view addSubview:_tableView];

2.配置delegate和DataSource(必须的方法)

 1 //配置每个section(段)有多少row(行) cell
 2 //默认只有一个section
 3 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 4     return 5;
 5 }
 6 //每行显示什么东西
 7 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 8     //给每个cell设置ID号(重复利用时使用)
 9     static NSString *cellID = @"cellID";
10     
11     //从tableView的一个队列里获取一个cell
12     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
13     
14     //判断队列里面是否有这个cell 没有自己创建,有直接使用
15     if (cell == nil) {
16         //没有,创建一个
17         cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
18         
19     }
20     
21     //使用cell
22     cell.textLabel.text = @"哈哈哈!!!";
23     return cell;
24 }

运行结果

可选方法

 1 //配置多个section
 2 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
 3     return 6;//6段
 4 }
 5 
 6 //设置高度
 7 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 8     return 60;
 9 }
10 
11 //某个cell被点击
12 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
13     //取消选择
14     [tableView deselectRowAtIndexPath:indexPath animated:YES];
15 }

效果

原文地址:https://www.cnblogs.com/frosting/p/9846551.html