2014-10-10 00:00

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

Github link

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

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

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

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

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

並且對 UITableView 加入 delegate 以及 datasource

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

	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:

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

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

Share

comments powered by Disqus