1. 程式人生 > >[Xcode10 實際操作]五、使用表格-(4)設定UITableView單元格資料庫源

[Xcode10 實際操作]五、使用表格-(4)設定UITableView單元格資料庫源

本文將演示如何自定義表格的資料來源。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

 1 import UIKit
 2 
 3 //首先新增兩個協議。
 4 //一個是表格檢視的代理協議UITableViewDelegate
 5 //另一個是表格檢視的資料來源協議UITableViewDataSource 
 6 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
 7     
 8     //建立一個數組,作為表格的資料來源
9 var weeks = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 10 11 override func viewDidLoad() { 12 super.viewDidLoad() 13 // Do any additional setup after loading the view, typically from a nib. 14 //建立一個位置在(0,40),尺寸為(320,420)的顯示區域 15
let rect = CGRect(x: 0, y: 40, width: 320, height: 420) 16 //初始化一個表格檢視,並設定其位置和尺寸資訊 17 let tableView = UITableView(frame: rect) 18 19 //設定表格檢視的代理,為當前的檢視控制器 20 tableView.delegate = self 21 //設定表格檢視的資料來源,為當前的檢視控制器 22 tableView.dataSource = self
23 24 //將表格檢視,新增到當前檢視控制器的根檢視中 25 self.view.addSubview(tableView) 26 } 27 28 //新增一個代理方法,用來設定表格檢視,擁有單元格的行數 29 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 30 //在此使用陣列的長度,作為表格檢視的行數 31 return weeks.count 32 } 33 34 //新增一個代理方法,用來初始化或複用表格檢視中的單元格 35 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 36 37 //建立一個字串,作為單元格的複用識別符號 38 let identifier = "reusedCell" 39 //單元格的識別符號,可以看作是一種複用機制。 40 //此方法可以從,所有已經開闢記憶體的單元格里面,選擇一個具有同樣識別符號的、空閒的單元格 41 var cell = tableView.dequeueReusableCell(withIdentifier: identifier) 42 43 //判斷在可重用單元格佇列中,是否擁有可以重複使用的單元格。 44 if(cell == nil) 45 { 46 //如果在可重用單元格佇列中,沒有可以重複使用的單元格, 47 //則建立新的單元格。新的單元格具有系統預設的單元格樣式,並擁有一個複用識別符號。 48 cell = UITableViewCell(style: .default, reuseIdentifier: identifier) 49 } 50 51 //索引路徑用來標識單元格在表格中的位置。它有section和row兩個屬性, 52 //section:標識單元格處於第幾個段落 53 //row:標識單元格在段落中的第幾行 54 let rowNum = (indexPath as NSIndexPath).row 55 //根據當前單元格的行數,從陣列中獲取對應位置的元素,作為當前單元格的標題文字 56 cell?.textLabel?.text = weeks[rowNum] 57 58 //返回設定好的單元格物件。 59 return cell! 60 } 61 62 override func didReceiveMemoryWarning() { 63 super.didReceiveMemoryWarning() 64 // Dispose of any resources that can be recreated. 65 } 66 }