1
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 3 years have passed since last update.

【Swift】画面遷移について

Posted at

遷移先の画面をstoryboard上で作る時の注意点

viewControllerを追加したら、この画面用のプログラムファイルが必要なので、①ファイルを用意して②遷移先の画面のclassにファイル名を追加する

ボタンをタップした場合の遷移

①遷移元の画面にButtonを追加する
Buttonからドラックアンドドロップして遷移先の画面に繋げる
Present Modallyを選択
④矢印(segue)が出てくる

modalで画面遷移を実装した場合、デフォルトでは背景に遷移元の画面が残るようになっているので、これを映らないようにするには
segueをクリック
presentationFull Screenに変更

戻る操作を実装するには
①遷移先の画面に戻る用のButtonを設置
戻るButtonを押しながらプログラムにドラックアンドドロップし、Actionを選択して名前をつける
③処理内容に

dismiss(animated: true, completion: nil)

を追加する。

任意のタイミングで画面遷移させる

例えば...
遷移元の画面にカウンターを実装し、カウント数が10になったら画面遷移させるという実装を行う場合...
(カウンターの数を表す変数をcountとする)
①遷移元画面のviewController上部に表示されているバーの黄色く丸いボタンから、遷移先の画面にドラックアンドドロップし、present Modallyを選択
②出現するsegueをクリックし、identifierに適当な名前をつける
③カウンターを実装しているメソッド内の処理に、

if count == 10{
  performSegue(withIdentifier: "segueのidentifierに設定した名前", sender: nil)
// (中略)
}

値を渡しながら画面遷移を行う場合

↑の続き
①遷移先の画面に、遷移元の画面から受け取りたい値を格納するための変数を設置
var count2 = 0とします
②遷移元の画面に

override func prepare(for segue: UIStoryBoardSegue, sender: Any?) {
  if (segue.identifier == "segueのidentifierに設定した名前") {
    let nextVC(自由に名前つける) = segue.destination as! 遷移先の画面の名前
    nextVC.count2 = count
  }
}

を記述
何をやっているかざっくり言うと、
①遷移元の画面に遷移先の画面を変数として宣言する(let~の部分)
②遷移先の画面に作った、受け取る値を格納するための変数を呼び出し、渡したい値を代入する
これで、遷移先に値を渡すことができます。

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