目前我們已經完成簡易訂單系統的新增訂單及刪除訂單,只要加上修改訂單的功能就算完成啦!
我們一樣利用將TableView往左滑的方式來修改訂單
而按下修改訂單的按鈕後會跳出UIAlertController來讓我們修改訂單名稱及金額
廢話不多說,馬上開始實做吧!
首先我們一樣需要這個function
但因為跟昨天所做的刪除都是將TableView往左滑來達成,只是需要新增一個修改訂單的按鈕,所以只要在同樣的function下新增程式碼就可以了~
//左滑修改
let modifyAction = UIContextualAction(style: .normal, title: "修改訂單") { (action, sourceView, complete) in
//呼叫提示框
func createAlert(alertTitle: String, alertMessage: String, actionTitle: String, cancleTitle: String, indexPath: IndexPath?)
{
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
let cancleAction = UIAlertAction(title: cancleTitle, style: .cancel, handler: nil)
let okAction = UIAlertAction(title: actionTitle, style: .default, handler: {
(action: UIAlertAction!) -> Void in
let modify: Order = Order()
let text0 = alert.textFields?[0].text
let text1 = alert.textFields?[1].text
modify.id = self.orders[indexPath!.row].setId
modify.name = text0!
modify.price = Int(text1!)!
try! self.realm.write {self.realm.add(modify, update: .all)}
self.allorders()
})
alert.addTextField { (titleTF) in
titleTF.placeholder = "訂單名稱"
}
alert.addTextField { (subtitleTF) in
subtitleTF.placeholder = "訂單價錢"
}
alert.addAction(okAction)
alert.addAction(cancleAction)
self.present(alert, animated: true, completion: nil)
}
createAlert(alertTitle: "修改", alertMessage: "", actionTitle: "確認", cancleTitle: "取消", indexPath: indexPath)
complete(true)
}
modifyAction.image = UIImage(systemName: "square.and.pencil")
modifyAction.backgroundColor = UIColor.systemYellow
Realm的修改訂單與新增訂單雷同,當時在這裡卡蠻久的
首先一樣要查詢訂單的id,再將訂單的名稱及價錢置換成UIAlertController裡面所輸入的內容就可以了!
最後記得要在UISwipeActionsConfiguration裡加入modifyAction
執行結果如下
如此一來,簡易的訂單系統就大功告成啦!!