1. 程式人生 > >[Xcode10 實際操作]五、使用表格-(7)UITableView單元格間隔背景色

[Xcode10 實際操作]五、使用表格-(7)UITableView單元格間隔背景色

本文將演示如何給表格設定間隔的背景顏色。

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

 1 import UIKit
 2 
 3 //首先新增兩個協議。
 4 //一個是表格檢視的代理協議UITableViewDelegate
 5 //另一個是表格檢視的資料來源協議UITableViewDataSource 
 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 12 //建立一個位置在(0,40),尺寸為(320,420)的顯示區域 13 let rect = CGRect(x: 0, y: 40, width: 320, height: 420) 14 //初始化一個表格檢視,並設定其位置和尺寸資訊 15 let tableView = UITableView(frame: rect)
16 17 //設定表格檢視的代理,為當前的檢視控制器 18 tableView.delegate = self 19 //設定表格檢視的資料來源,為當前的檢視控制器 20 tableView.dataSource = self 21 22 //將表格檢視,新增到當前檢視控制器的根檢視中 23 self.view.addSubview(tableView) 24 } 25 26 //新增一個代理方法,用來設定表格檢視,擁有單元格的行數 27 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
28 //在此設定表格檢視,擁有7行單元格 29 return 7 30 } 31 32 //新增一個代理方法,用來初始化或複用表格檢視中的單元格 33 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 34 35 //建立一個字串,作為單元格的複用識別符號 36 let identifier = "reusedCell" 37 //單元格的識別符號,可以看作是一種複用機制。 38 //此方法可以從,所有已經開闢記憶體的單元格里面,選擇一個具有同樣識別符號的、空閒的單元格 39 var cell = tableView.dequeueReusableCell(withIdentifier: identifier) 40 41 //判斷在可重用單元格佇列中,是否擁有可以重複使用的單元格。 42 if(cell == nil) 43 { 44 //如果在可重用單元格佇列中,沒有可以重複使用的單元格, 45 //則建立新的單元格。新的單元格具有系統預設的單元格樣式,並擁有一個複用識別符號。 46 cell = UITableViewCell(style: .default, reuseIdentifier: identifier) 47 } 48 49 //索引路徑用來標識單元格在表格中的位置。它有section和row兩個屬性, 50 //section:標識單元格處於第幾個段落 51 //row:標識單元格在段落中的第幾行 52 //獲取單元格在段落中的行數 53 let rowNum = (indexPath as NSIndexPath).row 54 //根據當前單元格的行數,生成一個序列化的字串,作為當前單元格的標題文字 55 cell?.textLabel?.text = "Cell item \(rowNum)" 56 57 //判斷段落的奇數偶數行 58 if(rowNum % 2 == 0) 59 { 60 //如果當前單元格處於段落的偶數行, 61 //則設定單元格背景顏色為紫色 62 cell?.backgroundColor = UIColor.purple 63 } 64 else 65 { 66 //如果當前單元格處於段落的奇數行, 67 //則設定單元格背景顏色為橙色 68 cell?.backgroundColor = UIColor.orange 69 } 70 71 //返回設定好的單元格物件。 72 return cell! 73 } 74 75 override func didReceiveMemoryWarning() { 76 super.didReceiveMemoryWarning() 77 // Dispose of any resources that can be recreated. 78 } 79 }