iOS| #26 | 使用TableView與Core Data實作ToDo App — 新增功能

Tommy
彼得潘的 Swift iOS / Flutter App 開發教室
5 min readMar 17, 2022

--

iOS| #23 | 使用TableView與Core Data實作ToDo App,這一次新增了兩項功能,以下就讓我們娓娓道來。

原先是實作func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath),透過點擊tableViewCell來打勾。但因為沒有處理到button的點擊event,所以點擊button時會沒有反應。

這一次的更新我們會把完成事項的功能做在UIButton上面,點擊tableViewCell則會進入detail頁面(僅供讀取無法編輯)。

功能解說&程式解說

  • 點擊Check Button可以完成事項

在override func tableView(_ tableView: , cellForRowAt indexPath: ) -> UITableViewCell根據indexPath.ro給予toDoButton.tag編號作為判斷第幾筆資料

cell.toDoButton.tag = indexPath.row

新增toDoButton.tag的處理事項

cell.toDoButton.addTarget(self, action: #selector(selectTodoButton), for: .touchUpInside)

實作func selectTodoButton(sender: ),從程式override func tableView(_ tableView: , cellForRowAt indexPath: ) -> UITableViewCell複製過來修改。其餘詳細解說可以參考iOS| #23 | 使用TableView與Core Data實作ToDo App

主要差異點在於原本是使用indexPath.row取得資料,現在改為使用sender.tag取得todoData。

@objc func selectTodoButton(sender: UIButton){  let todoData = todoDataList![sender.tag]  todoData.done.toggle()  do {    try ListCoreData.shared.updateData(todoData: todoData)  } catch let error {    showAlert(message: error.localizedDescription)  return}  tableView.reloadData()}
  • 新增讀取Detail頁面功能

為了控制點擊cell讀取Detail不能修改,所以在enum DataStatus新增選項read

enum DataStatus {  case insert , update , read}

在ListTableViewController新增屬性status,用來控制跳到Detail頁面的狀態。(預設為新增)

在Edit的按鈕控制屬性status為update

在點擊cell時控制屬性status為read

status = .read

取得當筆todoData

let todoData = todoDataList![indexPath.row]

呼叫performSegue去下一頁

self.performSegue(withIdentifier: "clickSwipeEditToEditController", sender: todoData)

status原本是寫死update,由於現在read與update都會call同一個@IBSegueAction,所以直接將屬性status傳到下一頁

若內容有誤煩請指教,感謝收看。

--

--