2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

(UIKit)segueを使わずに遷移させようとしたら、クラッシュしたんだが?

Last updated at Posted at 2023-08-19

こんな感じで動いて欲しかった

下のような感じで遷移させたかった。左はMainのView、右はAddView。
1.『右上のプラスボタン』を押す。
2.モーダル遷移でView(AddView)が表示される。
1.png

1.どんな場面で起こったのか?

『右上のプラスボタン』を押すとクラッシュしてしまった。
2.png

2.クラッシュの内容

Thread 1: "Storyboard () doesn't contain a view controller with identifier 'AddView'"

『そんなIDを持ったViewControllerはこのstoryboardにはない。』

3.問題のコードと、わかっていなかったこと

   //AddViewへ遷移させるためのボタン。
   //Buttonが置いてあるのはMainのViewController。
   @IBAction func toAddButtonAction(_ sender: Any) {
       let toAddView = storyboard?.instantiateViewController(withIdentifier: "AddView") as! AddViewController
       present(toAddView, animated: true)
     }
       
  • storyboardプロパティって何???
  • withIdentifierは間違っていないのになぜ???

4.解決

  @IBAction func toAddButtonAction(_ sender: Any) {
        let storyboard = UIStoryboard(name: "AddView", bundle: nil)
        let addView = storyboard.instantiateViewController(withIdentifier: "AddView") as! AddViewController
        let nav = UINavigationController(rootViewController: addView)
        addView.delegate = self
        present(nav, animated: true)
    }
  • まず、storyboardプロパティとは?

  • リファレンスによると、storyboardプロパティはViewControllerの元になるStoryboardだそうです。注意点は今回『右上のプラスボタン』を置いたのがMainのStoryboardだということ。紐付いているのはViewControllerです。
  • このViewControllerの中でstoryboardプロパティを使用すると、そのstoryboardプロパティはMainのStoryboardを指します。
  • クラッシュしたコードでは、画面をMainViewとAddViewを分けています。そのような場合、ViewControllerのstoryboardにはAddViewが持つIDは反映されないため、クラッシュを起こしてしまったと考えられます。

なので,以下の部分で明示的に名前を指定した後に、.instantiateViewControllerメソッドを使ってあげます。

//明示的に名前を指定
let storyboard = UIStoryboard(name: "AddView", bundle: nil)
let addView = storyboard.instantiateViewController(withIdentifier: "AddView") as! AddViewController

クラッシュは起こさずに遷移してくれるようになりました。

『.instantiateViewController() 』については以下を参照 

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?