[Swift-d22] - 實戰開發 - TODOList - Show View 1

鐵人賽 Swift Day22:TODOList 主頁建立假資料 dictionary array,傳入 TableView 顯示 todo id 和 content 列表,確認 UI 架構正常運作。

Github link

接著我們要讓主頁顯示一些假資料:

由於我們未來接的 api 的資料會是 todo_id + content

因此我們先產生一個 dictionary array 來存放我們的假資料

1
2
3
4
5
6
var fakeData = [[String:String]]()
fakeData = [
	["id": "1", "content": "A"],
	["id": "2", "content": "B"],
	["id": "3", "content": "C"],
]

再來對主頁的 controller 新增 tableView 上去

並且對 UITableView 加入 delegate 以及 datasource

 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
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var fakeData = [[String:String]]()
    var tableView: UITableView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        fakeData = [["1": "A"], ["2": "B"], ["3": "C"]]
        self.view.backgroundColor = UIColor.yellowColor()
        
        self.tableView = UITableView(frame: self.view.frame)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        
        self.view.addSubview(self.tableView!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

此時編譯器就會要求實作 UITableViewDataSource, UITableViewDelegate 的 methods

實作完就可以讓 TableView 顯示資料, 這我們之前也都有提到過了~

在這邊我們也同時使用自訂的 CustomTableViewCell, 簡單對 cell 改個顏色,雖然沒什麼多大用處 XD

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
	func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.fakeData.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: CustomTableViewCell? = tableView.dequeueReusableCellWithIdentifier("CustomCell") as? CustomTableViewCell
        
        if cell == nil {
            var objects = NSBundle.mainBundle().loadNibNamed("CustomTableViewCell", owner: self, options: nil)
            cell = objects[0] as? CustomTableViewCell
        }
        
        cell!.textLabel?.text = (self.fakeData[indexPath.row])["content"]
        
        return cell!
    }

image

不過可以看到有小瑕疵,就是選取後他並不會回覆成原本的模樣

因此加入 tableView didSelectRowAtIndexPath:

1
2
3
4
5
	func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        // 回復非選取狀態
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }

明天就會提到換頁以及刪除的作法!

comments powered by Disqus
Powered by Hugo. Theme Stack. All Rights Reserved.