LoginSignup
1
1

More than 1 year has passed since last update.

コードで画面遷移のやり方

Last updated at Posted at 2023-03-25

はじめに

コードで画面遷移するとき混乱したのでメモ、備忘録
ストーリーボードでsegue、ストーリーボードリファレンスでも画面遷移できますが条件をつけて遷移するときコードの方が便利!
今回はボタンで遷移させています。
テーブルビューのセルでも試して画面遷移できました。
サンプルです
https://github.com/kabikira/TestScreenTransition

同じstoryboard上で遷移したい場合

スクリーンショット 2023-03-25 20.04.58.png

storyboardIDを指定して行う。

// 同じストーリーボードに遷移したい画面があるとき
    @IBAction func goFristDetail(_ sender: Any) {
        if let vc = storyboard?.instantiateViewController(withIdentifier: "FirstDetail") as? FristDetailViewController {
            navigationController?.pushViewController(vc, animated: true)
        }
    }

ViewControllerのみの場合

スクリーンショット 2023-03-25 20.06.36.png

storyboardがなくViewControllerだけのときはこれだけ

    @IBAction func goSecondDetail(_ sender: Any) {
        // ViewControllerのみの場合
        let vc = SecondDetailViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

違うストーリーボードとViewControllerに遷移するとき

スクリーンショット 2023-03-25 20.06.54.png

storyboardの名前を指定して画面遷移します。

    @IBAction func goThirdDetail(_ sender: Any) {
        // 違うストーリーボードに遷移するとき
        if let vc = UIStoryboard(name: "ThirdDetail", bundle: nil).instantiateInitialViewController() as? ThirdDetailViewController {
            navigationController?.pushViewController(vc, animated: true)
        }
    }

おわりに

モダールで表示するときはpresentを使います

    @IBAction func goFristDetail(_ sender: Any) {
        // 同じストーリーボードに遷移したい画面があるとき
        if let vc = storyboard?.instantiateViewController(withIdentifier: "FirstDetail") as? FristDetailViewController {
            // モダールで遷移
            self.present(vc, animated: true)
        }
    }

間違ってたら教えてください!
サンプルです
https://github.com/kabikira/TestScreenTransition

1
1
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
1
1