前提・実現したいこと
学習のためCoreDataでtodoアプリを作りたく勉強しているのですが、2つTextFieldを用意してViewControllerのCellにある2つのLabelにTextFieldに入力したテキストを表示させたいのですが、以下の写真の状態になってしまう状態です
発生している問題・エラーメッセージ
1のTextFiedに「a」、2のTextFieldに「b」を入力したのですが、アプリを立ち上げるとcellには「a」しか表示されていない状況です。
ご教示頂けると幸いです。
import UIKit import CoreData class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{ @IBOutlet weak var tableView: UITableView! var oneBox:[ToDo] = [] var twoBox:[ToDo] = [] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { goData() tableView.reloadData() } func goData() { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext do { let fetchRequest: NSFetchRequest<ToDo> = ToDo.fetchRequest() oneBox = try context.fetch(fetchRequest) twoBox = try context.fetch(fetchRequest) } catch { print("Error") } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return oneBox.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let todoCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.reuseIdentifier, for: indexPath) as? TableViewCell else { fatalError("Error") } todoCell.oneLabel.text = oneBox[indexPath.row].one todoCell.twoLabel.text = twoBox[indexPath.row].two return todoCell } }
import UIKit class addViewController: UIViewController { @IBOutlet weak var textFiedOne: UITextField! @IBOutlet weak var textFieldTwo: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func addButton(_ sender: Any) { let oneName = textFiedOne.text let twoName = textFieldTwo.text let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let todo = ToDo(context: context) todo.one = oneName todo.two = twoName (UIApplication.shared.delegate as! AppDelegate).saveContext() dismiss(animated: true, completion: nil) } }
import UIKit class TableViewCell: UITableViewCell { static var reuseIdentifier = "todoCell" @IBOutlet var oneLabel: UILabel! @IBOutlet var twoLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
補足情報(FW/ツールのバージョンなど)
Swift5 Xode10
あなたの回答
tips
プレビュー