iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0

上一篇文章提到,傳值的部分使用Closure傳值,但是細節部分我還沒提到,並且目前修改的功能也缺少修改頁面將值回傳的功能,

還記得我昨天在ModifyViewController類別內實作了savingModify()方法嗎?:

func savingModify()
    {
        if let text0 = modifyTV.text, let text1 = modifyTF.text{
            let data = ListModel(title: text0, subtitle: text1)
            `passingToATVCClosure?(data)`
            navigationController?.popToRootViewController(animated: true)
        }
        
    }

其中有一行程式碼是這樣的,這行的意思是我把data丟進閉包內,目前的data儲存了一筆ListModel資料,但是此時我的閉包還沒有實作任何事情,所以即使把data丟進passingToATVCClosure內,依然不會發生任何事情,所以必須這個閉包內要幹些什麼事情,就由我們來實作,至於在哪裡實作,在你希望資料傳到的目標實作,我希望資料傳遞到ListViewController內,並且取代listDatas內未修改前的資料,並且在表格更改,所以我在ListViewController實作,至於要在這個類別內的哪裡實作,我選擇在點選修改按鈕後頁面跳轉的那個地方實作,因為在這個地方我可以要得到ModifyViewController內的屬性,也就是passingToATVCClosure,現在你的modifyAction的程式碼應該看起來像這樣子:

 let modifyAction = UIContextualAction(style: .normal, title: "修改") { (action, sourceView, complete) in
              let oldValue = self.listDatas[indexPath.row]
              self.indexPath = indexPath
              let destinationVC = self.storyboard?.instantiateViewController(identifier: "ModifyViewController") as! ModifyViewController
              destinationVC.listData = oldValue
              
             //實作閉包的地方,這段程式碼內的listData其實就是ModifyViewController的savingModify()內丟進閉包的data
              destinationVC.passingToATVCClosure = {(listData) in
                  self.listDatas[indexPath.row] = listData
              }
              
              
              self.show(destinationVC, sender: self)
              complete(true)
          }

現在你的修改功能至此為止已經完成了,並且修改完按下儲存後,回到首頁,完成了我只想要更新特定行數的功能,並非全部更新。


如果你仔細看我在第一天放的完整實作的圖,會發現往右滑其實也有一個分享動作,現在我們來實作它,在tableView(:leadingSwipeActionsConfigurationForRowAt:)方法內加入下列程式碼:

let shareAction = UIContextualAction(style: .destructive, title: "分享") { (action, sourceView, complete) in
              let defaultText = "我於\(self.listDatas[indexPath.row].subtitle)時,要\(self.listDatas[indexPath.row].title)"
              let shareController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil)
              self.present(shareController, animated: true, completion: nil)
              complete(true)
          }
          shareAction.image = UIImage(systemName: "square.and.arrow.up")
          shareAction.backgroundColor = UIColor.systemOrange
          let leadingSwipeConfiguration = UISwipeActionsConfiguration(actions: [shareAction])
          return leadingSwipeConfiguration

現在往右滑也可以帶出分享動作了,作法與左滑很像。

到目前為止已經完成了大部分的功能了,但是如果你仔細想想,還剩下最重要的一點,將資料儲存在手機上,你不會想要滑掉App之後,你的待辦資料都不見吧,那看起來很蠢,所以我們必須加入儲存到手機的功能,明天接著講。


上一篇
Day5-實作To-Do-List之修改(頁面傳值/closure傳值)
下一篇
Day7-實作To-Do-List之儲存與讀取功能(UserDefault)
系列文
想知道自己iOS具現化系能力有多強嗎?實作幾個App就知道了30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言