[Xcode10 实际操作]五、使用表格-(2)设置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     //添加一个代理方法,用来设置表格行的高度为80
32     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
33         //设置表格行的高度为80
34         return 80
35     }
36     
37     //添加一个代理方法,用来初始化或复用表格视图中的单元格
38     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
39         
40         //创建一个字符串,作为单元格的复用标识符
41         let identifier = "reusedCell"
42         //单元格的标识符,可以看作是一种复用机制。
43         //此方法可以从,所有已经开辟内存的单元格里面,选择一个具有同样标识符的、空闲的单元格
44         var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
45         
46          //判断在可重用单元格队列中,是否拥有可以重复使用的单元格。
47         if(cell == nil)
48         {
49             //如果在可重用单元格队列中,没有可以重复使用的单元格,
50             //则创建新的单元格。新的单元格具有系统默认的单元格样式,并拥有一个复用标识符。
51             cell = UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
52         }
53 
54         //默认样式的单元格,拥有一个标签对象,在此设置标签对象的文字内容。
55         cell?.textLabel?.text = "Cell title here."
56         //在标签对象的下方,还有一个字体较小的描述文字标签,
57         //同样设置该标签对象的文字内容
58         cell?.detailTextLabel?.text = "Detail information here."
59         
60         //返回设置好的单元格对象。
61         return cell!
62     }
63 
64     override func didReceiveMemoryWarning() {
65         super.didReceiveMemoryWarning()
66         // Dispose of any resources that can be recreated.
67     }
68 }

猜你喜欢

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