目錄:[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 //默認樣式的單元格,擁有一個標籤對象,在此設置標籤對象的文字內容。 50 cell?.textLabel?.text = "Title Information" 51 52 //索引路徑用來標識單元格在表格中的位置。它有section和row兩個屬性, 53 //section:標識單元格處於第幾個段落 54 //row:標識單元格在段落中的第幾行 55 //獲取單元格在段落中的行數 56 let rowNum = (indexPath as NSIndexPath).row 57 58 //若是處於第2行,則設置該單元格的背景顏色爲黃色(第一行索引爲0) 59 if(rowNum == 1) 60 { 61 cell?.backgroundColor = UIColor.yellow 62 } 63 else 64 { 65 //建立一個位置在(0,0),尺寸爲(100,100)的顯示區域 66 let rect = CGRect(x: 0, y: 0, width: 100, height: 100) 67 //並初始化一個視圖,同時設置其位置和尺寸信息 68 let view = UIView(frame: rect) 69 //設置視圖的背景顏色爲棕色 70 view.backgroundColor = UIColor.brown 71 72 //而後將設置好的視圖,做爲單元格的背景視圖 73 cell?.backgroundView = view 74 } 75 76 //返回設置好的單元格對象。 77 return cell! 78 } 79 80 override func didReceiveMemoryWarning() { 81 super.didReceiveMemoryWarning() 82 // Dispose of any resources that can be recreated. 83 } 84 }