1. 程式人生 > >[Xcode10 實際操作]五、使用表格-(2)設定UITableView單元格高度

[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 }