[Swift-d23] - 實戰開發 - TODOList - Show View 2, Delete View
延續昨天,接下來要做換頁
因此我們必須先新建立一個 ShowViewController, 以及他的 xib
接著我們在 xib 拉幾個元件: 兩個 label, 一個用來顯示目前的 index, 另一個則是顯示內容
拉好後,將這兩個元件設定連結到 ShowViewController.swift
另外多在 ShowViewController 中放兩個變數
var index: Int!
var content: String!
回到 ViewController, 到 tableView didSelectRowAtIndexPath 中
因為 didSelectRowAtIndexPath 的意思就是當 cell 被選取時要做什麼事情
因此當 cell 被選取時,我們就要讓他跳到下一頁,並且是使用 ShowViewController 來顯示資料
因此修改此方法:
	func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var showViewController = ShowViewController(nibName: "ShowViewController", bundle: nil)
        showViewController.index = indexPath.row
        showViewController.content = fakeData[indexPath.row]["content"]
        
        // 回復非選取狀態
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        self.navigationController?.pushViewController(showViewController, animated: true)
    }
最後在 ShowViewController 中的 viewDidLoad 加入:
        indexLabel.text = "\(index)"
        contentLabel.text = content
這樣一來在 ShowViewController 被建立時,顯示的 label 就會將上一個 view 設定的 index, content 的值顯示出來了
執行看看!
這樣 Show 的部分就完成了!
接著我們回到主頁
要來建立將 cell 向左滑可以刪除的事件,這是 iOS 內建的事件,
因此建立方法也很簡單:
一樣是覆寫 tableView 的方法
要讓 tableView 可以編輯 row - canEditRowAtIndexPath
	func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
按下確認刪除後的行為 - 我們在這邊實際上是刪除 fakeData 的值
所以只要 App 重開後就又會回到三筆資料了
	func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        self.fakeData.removeAtIndex(indexPath.row)
        
        dispatch_async(dispatch_get_main_queue(), {
            // must be "tableView!" not "tableView?"
            self.tableView!.reloadData()
        })
        let alert = UIAlertView()
        alert.title = "Alert"
        alert.message = "Deleted!"
        alert.addButtonWithTitle("Ok")
        alert.show()
    }
這樣我們就有顯示單筆以及顯示多筆還有刪除可以用了!