Swift - 使用storyboard創建表格視圖(TableViewController)


項目創建完畢后,默認是使用ViewController作為主界面視圖。下面通過樣例演示,如何使用TableViewController作為主界面視圖,同時演示如何在storyboard中設置表格及內部單元格樣式。


功能如下:
1,程序運行后即為表格頁面
2,表格內容為“行號:內容”
3,點擊單元格可以切換勾選與取消勾選狀態

效果圖如下:

詳細步驟:
1,刪掉storyboard現有的視圖界面。然后從對象庫中拖入一個TableViewController到場景中。同時將其Attributes面板中的,Is Initial View Controller選中。

2,新建一個類MainController.swift,繼承自UITableViewController

3,將場景中的TableViewController與新建的MainController進行綁定。選中主界面,然后再Identity面板中將CustomClass的Class屬性設置為MainController即可。

4,選中單元格(TableViewCell),在Attributes面板中設置Identifier屬性為“maincell”(供代碼中使用)。
同時將Accessory屬性設置為Checkmark(表示單元格尾部為勾號)

5,從對象庫中拖入一個Label控件到cell中,用於顯示內容。同時選中這個Label,在Attributes面板中設置Tag的值為1000,供代碼中獲取標簽。

6,MainController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import UIKit
 
class MainController : UITableViewController {
     
     var tasks:[ String ] = [ "今天任務" , "明天任務" , "后天任務" ]
 
     override func viewDidLoad() {
         super .viewDidLoad()
     }
 
     override func didReceiveMemoryWarning() {
         super .didReceiveMemoryWarning()
     }
 
     override func tableView(tableView: UITableView , numberOfRowsInSection section: Int ) -> Int {
         return tasks.count
     }
 
     override func tableView(tableView: UITableView , cellForRowAtIndexPath indexPath: NSIndexPath )
         -> UITableViewCell {
         let cell = tableView.dequeueReusableCellWithIdentifier( "maincell" , forIndexPath: indexPath)
             as UITableViewCell
         //獲取label
         let label = cell.viewWithTag(1000) as UILabel
         //設置label內容
         label.text = "\(indexPath.row):\(tasks[indexPath.row])"
         return cell
     }
     
     override func tableView(tableView: UITableView , didSelectRowAtIndexPath indexPath: NSIndexPath ) {
         //獲取cell
         let cell = tableView.cellForRowAtIndexPath(indexPath)
         //根據原先狀態,改變勾選或取消勾選狀態
         if cell?.accessoryType == UITableViewCellAccessoryType . None {
             cell?.accessoryType = UITableViewCellAccessoryType . Checkmark
         } else {
             cell?.accessoryType = UITableViewCellAccessoryType . None
         }
         //取消選中狀態
         tableView.deselectRowAtIndexPath(indexPath, animated: true )
     }
}

7,上述操作完畢后會發現,表格頂着最上面不好看。我們可以在頭部添加一個Navigation Controller導航控制器。即選中storyboard中的主界面,然后從XCode的頂部菜單選擇Editor->Embed In->Navigation Controller。最后,選擇主界面,將title設置為“任務列表”  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM