LoginSignup
0
1

More than 3 years have passed since last update.

画面の遷移方法まとめ【Swift】

Last updated at Posted at 2021-03-27

Swift勉強2日目、自分用の備忘録です。

Swiftで画面遷移をする方法は以下の3つ。
①ボタンを押して遷移(ノーコード)
②セグエで遷移
③ナビゲーションコントローラーで遷移

①ボタンを押して遷移(ノーコード)

ボタンをcontrol押しながら遷移先のVCにドラッグ&ドロップ

②セグエで遷移(値を渡さない時)

  1. セグエにIdentifierを付与
  2. コードを実装
// 遷移
performSegue(withIdentifier: "next", sender: nil)

②セグエで遷移(値を渡す時)

  1. セグエにIdentifierを付与(Storyboard Segue)
  2. コードを実装
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // 遷移先のVCを変数にいれる
    let nextVC = segue.destination as! NextViewController
    // 遷移先のVCの変数(count)に渡したい値をいれる
    nextVC.count = "foo"
}    

// 遷移
performSegue(withIdentifier: "next", sender: nil)

③ナビゲーションコントローラーで遷移

  1. Editor > Embed In > Navigation Controllerからナビゲーションコントローラーを追加
  2. 遷移先のビューコントローラーにStoryboard IDを付与
  3. コードを実装
// 遷移先のVCを変数に代入
let nextVC = storyboard?.instantiateViewController(withIdentifier: "next") as! NextViewController
// (遷移先のVCの変数(todoString)に値を代入)        
nextVC.todoString = "" 
// 遷移        
navigationController?.pushViewController(nextVC, animated: true)

戻るボタン

@IBAction func back(_ sender: Any) {
    dismiss(animated: true, completion: nil)  // この一行でOK
}
0
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
0
1