2014-10-10 00:00

[Swift-day25] - 實戰開發 - TODOList - Update View

Github link

(忘了是放在哪個 branch 了 Orz)

接下來就要進到最後一個 Update View 了!

什麼時候會進到 Update View 呢?

是在顯示單筆 TODO 的時候的右上方按鈕:

image

我們今天只會實作 view 的部分, fakeData 就不實作了

因為接下來就要直接接 API 啦

也不需要更新 fakeData 了 :P

要加入 Edit 這個按鈕

要到 ShowViewController, 加入 UIBarButtonItem

並且讓其吃到一個方法,可以讓 Navigation 往下一個 View 前進:

var id: String!

override func viewDidLoad() {
        super.viewDidLoad()
        
        indexLabel.text = "\(index)"
        contentLabel.text = content
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: UIBarButtonItemStyle.Bordered, target: self, action: Selector("editTodo"))
    }

p.s. 先前忘記加了 id, 現在補回來 XD

先新增一個 Edit 按鈕後

並實作 editTodo

func editTodo() {
        var editViewContronller = UpdateViewController(nibName: "UpdateViewController", bundle: nil)
        editViewContronller.from = "edit"
        editViewContronller.content = content
        editViewContronller.index = index
        
        self.navigationController?.pushViewController(editViewContronller, animated: true)
    }

由於要先指定資料

因此再到 UpdateViewController 中再加入兩個參數

    var index: Int!
    var content: String!

最後在 UpdateController 的 viewDidLoad 中, 加入 add or edit 的判斷

override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Done, target: self, action: Selector("save"))
			
		  if self.from == "edit" {
            self.textField.text = content
        }
        
    }

這時候先前設定的 “from” 參數就很有用了~

就可以根據是從 add 的 view 來的或者是 edit 的 view 來的

以便判定要不要 append 舊資料上去

此外,也因為如此

所以 UpdateViewController 的 save 方法也要判斷

        if from == "add" {
            delegate.addData("g6", content: self.textField.text)
            self.navigationController?.popToRootViewControllerAnimated(true)
        } else if from == "edit" {
            println("Save edited data")
        }

不過因為今天我們不做資料更新

因此流程面大致上到此告一個段落

接下來就要串 API 了!

Share

comments powered by Disqus