[Xcode 實際操做]5、使用表格-(7)UITableView單元格間隔背景色

目錄:[Swift]Xcode實際操做html

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

在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】ide

 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 }
相關文章
相關標籤/搜索