前提・実現したいこと
navigationControllerをしており画面遷移の際に、遷移元画面の入力フォームに記入された値を、遷移先のViewControllerに渡したいと思っています。
しかし、遷移先のViewControllerのIBOutletプロパティがnilになってしまいます。
構成としては下記の通りです。
遷移元ViewController
- navigationControllerを使用
- TableViewControllerでstatic cellを使用
- static cellの中にTextFieldとButtonを配置
- コードで生成したButtonをタップした際に画面遷移(コードで記述)
遷移先ViewController
- navigationControllerを使用
- TableViewControllerでstatic cellを使用
- IBOutlet(Label)はstatic cellの要素
発生している問題・エラーメッセージ
Fatal error: Unexpectedly found nil while unwrapping an Optional value
該当のソースコード
遷移元 ViewController1
swift
1import UIKit 2 3class ViewController1: UITableViewController { 4 5 @IBOutlet var tableView: UITableView! 6 var cell: UITableViewCell! 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 } 11 12 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 13 14 cell = super.tableView(tableView, cellForRowAt: indexPath) 15 16 // 入力フォームView 17 let frame = CGRect(x: 0, 18 y: 0, 19 width: self.view.frame.width, 20 height: self.view.frame.height) 21 let editView = EditView(frame: frame) 22 cell.contentView.addSubview(editView) 23 24 // 確認ボタン 25 let nextButtonFrame = CGRect(x: 16.0, 26 y: editView.bounds.height, 27 width: self.view.frame.width, 28 height: 44.0) 29 let nextButton = UIButton(frame: nextButtonFrame) 30 nextButton.addTarget(self, action: #selector(pushNextButton(_:)), for: .touchUpInside) 31 cell.contentView.addSubview(nextButton) 32 33 return cell 34 } 35 36 @objc func pushNextButton(_ sender: UIButton) { 37 // ここで遷移先のViewControllerを作成しています 38 let storyboard = UIStoryboard(name: "ViewController2", bundle: Bundle.main) 39 guard let vc = storyboard.instantiateInitialViewController() as? ViewController2 else { 40 fatalError("no exist ViewController2") 41 } 42 43 // 入力フォームのオブジェクトを取り出します 44 let editView = cell.contentView.subviews[0] as? EditView 45 guard sessionEditView != nil else { 46 fatalError("no exist cell") 47 } 48 49 // 入力フォームのテキストフィールドに入力されたテキストを遷移先に渡そうとするが 50 // ここでtitleLabelがnilになる 51 vc.titleLabel.text = editView?.titleTextField.text 52 53 navigationController?.pushViewController(vc, animated: true) 54 } 55}
遷移先 ViewController2
swift
1import UIKit 2 3class ViewController2: UITableViewController { 4 5 // MARK: - IBOutlet Properties 6 @IBOutlet weak var titleLabel: UILabel! 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 11 // Do any additional setup after loading the view. 12 } 13} 14
補足情報
swift4
Xcode10.2
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。