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 }

效果

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM