[Xcode10 实际操作]五、使用表格-(1)使用UITableView制作简单表格

本文将演示表格视图的使用方法。

在项目导航区,打开视图控制器的代码文件【ViewController.swift】

 1 import UIKit
 2 
 3 //首先添加两个协议。
 4 //一个是表格视图的代理协议UITableViewDelegate
 5 //另一个是表格视图的数据源协议
 6 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
 7 
 8     override func viewDidLoad() {
 9         super.viewDidLoad()
10         // Do any additional setup after loading the view, typically from a nib.
11         //创建一个位置在(0,40),尺寸为(320,420)的显示区域
12         let rect = CGRect(x: 0, y: 40, width: 320, height: 420)
13         //初始化一个表格视图,并设置其位置和尺寸信息
14         let tableView = UITableView(frame: rect)
15         
16         //设置表格视图的代理,为当前的视图控制器
17         tableView.delegate = self
18         //设置表格视图的数据源,为当前的视图控制器
19         tableView.dataSource = self
20         
21         //将表格视图,添加到当前视图控制器的根视图中
22         self.view.addSubview(tableView)
23     }
24     
25     //添加一个代理方法,用来设置表格视图,拥有单元格的行数
26     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
27        //在此设置表格视图,拥有5行单元格
28         return 5
29     }
30     
31     //添加一个代理方法,用来初始化或复用表格视图中的单元格
32     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
33         
34         //创建一个字符串,作为单元格的复用标识符
35         let identifier = "reusedCell"
36         //单元格的标识符,可以看作是一种复用机制。
37         //此方法可以从,所有已经开辟内存的单元格里面,选择一个具有同样标识符的、空闲的单元格
38         var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
39         
40         //判断在可重用单元格队列中,是否拥有可以重复使用的单元格。
41         if(cell == nil)
42         {
43             //如果在可重用单元格队列中,没有可以重复使用的单元格,
44             //则创建新的单元格。新的单元格具有系统默认的单元格样式,并拥有一个复用标识符。
45             cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: identifier)
46         }
47         
48         //默认样式的单元格,拥有一个标签对象,在此设置标签对象的文字内容。
49         cell?.textLabel?.text = "Cell title here."
50         //在标签对象的下方,还有一个字体较小的描述文字标签,
51         //同样设置该标签对象的文字内容
52         cell?.detailTextLabel?.text = "Detail information here."
53         
54         //返回设置好的单元格对象。
55         return cell!
56     }
57 
58     override func didReceiveMemoryWarning() {
59         super.didReceiveMemoryWarning()
60         // Dispose of any resources that can be recreated.
61     }
62 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10018502.html