[Xcode 實際操做]5、使用表格-(3)設置UITableView單元格圖標

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

本文將演示如何給表格行設置圖標。swift

打開資源文件夾【Assets.xcassets】,ide

在資源文件夾中導入兩張圖片:一張彩色,一張灰色,做爲單元格的圖標。post

【+】->【Import】->【Open】字體

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

 1 import UIKit
 2 
 3 //首先添加兩個協議。
 4 //一個是表格視圖的代理協議UITableViewDelegate
 5 //另外一個是表格視圖的數據源協議UITableViewDataSource 
 6 class ViewController: UIViewController, UITableViewDelegate
 7 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
 8 
 9     override func viewDidLoad() {
10         super.viewDidLoad()
11         // Do any additional setup after loading the view, typically from a nib.
12 
13         //建立一個位置在(0,40),尺寸爲(320,420)的顯示區域
14         let rect = CGRect(x: 0, y: 40, width: 320, height: 420)
15         //初始化一個表格視圖,並設置其位置和尺寸信息
16         let tableView = UITableView(frame: rect)
17         
18         //設置表格視圖的代理,爲當前的視圖控制器
19         tableView.delegate = self
20         //設置表格視圖的數據源,爲當前的視圖控制器
21         tableView.dataSource = self
22         
23         //將表格視圖,添加到當前視圖控制器的根視圖中
24         self.view.addSubview(tableView)
25     }
26     
27     //添加一個代理方法,用來設置表格視圖,擁有單元格的行數
28     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
29         //在此設置表格視圖,擁有5行單元格
30         return 5
31     }
32     
33     //添加一個代理方法,用來初始化或複用表格視圖中的單元格
34     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
35         
36         //建立一個字符串,做爲單元格的複用標識符
37         let identifier = "reusedCell"
38         //單元格的標識符,能夠看做是一種複用機制。
39         //此方法能夠從,全部已經開闢內存的單元格里面,選擇一個具備一樣標識符的、空閒的單元格
40         var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
41         
42         //判斷在可重用單元格隊列中,是否擁有能夠重複使用的單元格。
43         if(cell == nil)
44         {
45             //若是在可重用單元格隊列中,沒有能夠重複使用的單元格,
46             //則建立新的單元格。新的單元格具備系統默認的單元格樣式,並擁有一個複用標識符。
47             cell = UITableViewCell(style: .subtitle, reuseIdentifier: identifier)
48         }
49         
50         //默認樣式的單元格,擁有一個標籤對象,在此設置標籤對象的文字內容。
51         cell?.textLabel?.text = "Cell title here."
52         //在標籤對象的下方,還有一個字體較小的描述文字標籤,
53         //一樣設置該標籤對象的文字內容
54         cell?.detailTextLabel?.text = "Detail information here."
55         
56         //讀取剛剛導入的彩色的圖片素材
57         let star = UIImage(named: "Star")
58         //讀取剛剛導入的灰色的圖片素材
59         let starGray = UIImage(named: "StarGray")
60         
61         //將灰色的圖片,做爲單元格的默認圖標
62         cell?.imageView?.image = starGray
63         //將彩色的圖片,做爲做爲單元格的高亮圖標
64         cell?.imageView?.highlightedImage = star
65         
66         //返回設置好的單元格對象。
67         return cell!
68     }
69 
70     override func didReceiveMemoryWarning() {
71         super.didReceiveMemoryWarning()
72         // Dispose of any resources that can be recreated.
73     }
74 }
相關文章
相關標籤/搜索