Swiftで行こう!-- TableView 遷移、入力!
これを参考に、記録しておきます。
こんな感じにしたい。
1. テーブルのあるセルを選びクリック。
2. 入力する(入力終わるまでsaveボタン無効。入力してreturnするとsaveボタン有効になり押すと遷移)
3 元のテーブルに戻る(新しくデータが入力されている)
全体像です。
データを新規に追加する場合と、テーブルセルを選んで修正する場合を考えます。
新規の場合はデータの追加をしないといけません。テーブルにもデータを追加しないといけません。
テーブルにある項目に関しては、データの修正する必要がありますね。
新規で追加する場合ですが、
let newIndexPath = IndexPath(row: arrs.count, section: 0)
arrs.append(arr)
tableView.insertRows(at: [newIndexPath], with: .automatic)
修正する場合
let newIndexPath = IndexPath(row: arrs.count, section: 0)
arrs.append(arr)
tableView.insertRows(at: [newIndexPath], with: .automatic)
とすればうまくいきます。
@IBAction func unwindToMealList(sender: UIStoryboardSegue){}
を使います。戻ってくるタイミングで実行するので、TableViewController.swiftに記述して場合分けします。
全体です。
@IBAction func unwindToMealList(sender: UIStoryboardSegue){
if let sourceViewController = sender.source as? ViewController, let arr = sourceViewController.arrs {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
arrs[selectedIndexPath.row] = arr
tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
else {
let newIndexPath = IndexPath(row: arrs.count, section: 0)
arrs.append(arr)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
if let selectedIndexPath = tableView.indexPathForSelectedRow
これでセルを選択してデータを修正させる場合を認識した場合は
上書きして、それ以外はelse以下の命令を実行するという感じです。
これで、画面が戻ったときには新規と上書きを選択してデータの反映を行います。
データを移行する場合には遷移元でも準備をしないといけません。ではその準備です。遷移元のViewController.swiftに書いていきます。
override func prepare(for segue: UIStoryboardSegue, sender: Any?){}
を使います。全体です。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
let name = textField.text ?? ""
arrs = DataSet(name: name)
}
let button = sender as? UIBarButtonItem, button === saveButton
としていて、saveButtonが押されたときにtextField.textで取得したデータをarrs = DataSet(name: name)でセットします。次の画面、戻った画面でデータがセットされます。
長くなったので、この辺で次に回します。